android Service中多線程交互
android 的service和activity是執行在UI主線程的。
在android線程中,僅僅有主線程即UI線程有自己的默認的消息隊列。子線程須要創建自己的消息隊列。並把消息發給隊列,並循環起來,發給handler處理。
1、Looper.prepare();給子線程創建消息隊列。
2、Looper.loop();把消息放入消息隊列並循環起來。
例如以下是一個通過activity的oncreate()方法啟動服務,在服務裏開啟子線程,並發消息給主線程來處理的DEMO。
3、MainActivity.java例如以下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(MainActivity.this,ServiceTest.class));
}
4、ServiceTest.java
public class ServiceTest extends Service {
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
new Thread(){
@Override
public void run() {
Log.i("服務", "第2個線程");
Looper.prepare();
for(int i=10;i<20;i++){
try {
//Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
mHandler.sendEmptyMessage(2);
Looper.loop();
};
}.start();
break;
case 2:
new Thread(){
@Override
public void run() {
Log.i("服務", "第3個線程");
Looper.prepare();
for(int i=20;i<30;i++){
try {
//Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
mHandler.sendEmptyMessage(3);
Looper.loop();
};
}.start();
break;
case 3:
onDestroy();
break;
default:
break;
}
super.handleMessage(msg);
}
};
public ServiceTest() {
// TODO Auto-generated constructor stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Log.i("服務", "onCreate()");
super.onCreate();
new Thread(){
@Override
public void run() {
Log.i("服務", "第一個線程");
Looper.prepare();
for(int i=0;i<10;i++){
Toast.makeText(getApplicationContext(), i+"",0).show();
try {
//Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
mHandler.sendEmptyMessage(1);
Looper.loop();
};
}.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("服務", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("服務", "onDestroy()");
super.onDestroy();
stopSelf();
}
}
附:demo下載地址http://download.csdn.net/detail/u014600432/8104521
android Service中多線程交互