程序员人生 网站导航

android Service中多线程交互

栏目:互联网时间:2014-11-08 08:03:09

android 的service和activity是运行在UI主线程的。在android线程中,只有主线程即UI线程有自己的默许的消息队列。子线程需要创建自己的消息队列,并把消息发给队列,并循环起来,发给handler处理。

1、Looper.prepare();给子线程创建消息队列。

2、Looper.loop();把消息放入消息队列并循环起来。

以下是1个通过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++){
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("服务", "第3个线程");
Looper.prepare();
for(int i=20;i<30;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("服务", "onCreate()");
super.onCreate();
new Thread(){
@Override
public void run() {
Log.i("服务", "第1个线程");
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


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐