新聞中心

android Service中多線程交互

作者: 時(shí)間:2016-09-12 來(lái)源:網(wǎng)絡(luò) 收藏

android 的service和activity是運(yùn)行在UI主線程的。在android線程中,只有主線程即UI線程有自己的默認(rèn)的消息隊(duì)列。子線程需要?jiǎng)?chuàng)建自己的消息隊(duì)列,并把消息發(fā)給隊(duì)列,并循環(huán)起來(lái),發(fā)給handler處理。

本文引用地址:http://butianyuan.cn/article/201609/304411.htm

1、Looper.prepare();給子線程創(chuàng)建消息隊(duì)列。

2、Looper.loop();把消息放入消息隊(duì)列并循環(huán)起來(lái)。

如下是一個(gè)通過(guò)activity的oncreate()方法啟動(dòng)服務(wù),在服務(wù)里開(kāi)啟子線程,并發(fā)消息給主線程來(lái)處理的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個(gè)線程);

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個(gè)線程);

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ù), 第一個(gè)線程);

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();

}

}



關(guān)鍵詞:

評(píng)論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉