android Service中多線程交互
android 的service和activity是運行在UI主線程的。在android線程中,只有主線程即UI線程有自己的默認(rèn)的消息隊列。子線程需要創(chuàng)建自己的消息隊列,并把消息發(fā)給隊列,并循環(huán)起來,發(fā)給handler處理。
本文引用地址:http://m.butianyuan.cn/article/201609/304411.htm1、Looper.prepare();給子線程創(chuàng)建消息隊列。
2、Looper.loop();把消息放入消息隊列并循環(huán)起來。
如下是一個通過activity的oncreate()方法啟動服務(wù),在服務(wù)里開啟子線程,并發(fā)消息給主線程來處理的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(服務(wù), 第2個線程);
Looper.prepare();
for(int i=10;i20;i++){
Toast.makeText(getApplicationContext(), i+,0).show();
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(服務(wù), 第3個線程);
Looper.prepare();
for(int i=20;i30;i++){
Toast.makeText(getApplicationContext(), i+,0).show();
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(服務(wù), onCreate());
super.onCreate();
new Thread(){
@Override
public void run() {
Log.i(服務(wù), 第一個線程);
Looper.prepare();
for(int i=0;i10;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(服務(wù), onStartCommand);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i(服務(wù), onDestroy());
super.onDestroy();
stopSelf();
}
}
評論