Android使用Messenger实现service与activity交互

2019/7/7 19:44:33

本文主要是介绍Android使用Messenger实现service与activity交互,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

service与activity交互的方式有多种,这里说说使用Messenger来实现两者之间的交互。

Service程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class MessengerService extends Service {
 
 final Messenger mMessenger = new Messenger(new IncomingHandler());
 @Override
 public IBinder onBind(Intent intent) {
  return mMessenger.getBinder();
 }
 
 @SuppressLint("HandlerLeak")
 class IncomingHandler extends Handler {
 
  @Override
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case 0:
    Toast.makeText(MessengerService.this,"Hello lenve!", Toast.LENGTH_LONG).show();
    break;
   case 1:
    Toast.makeText(MessengerService.this,"Hello lenve!Hello world!", Toast.LENGTH_LONG).show();
    break;
   default:
    break;
   }
  }
 
 }
}

MainActivity.javaL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class MainActivity extends Activity {
 
 private Messenger mMessenger;
 private ServiceConnection conn;
 private Intent intent;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  intent = new Intent(this,MessengerService.class);
  conn = new ServiceConnection() {
 
   @Override
   public void onServiceDisconnected(ComponentName name) {
    mMessenger = null;
   }
 
   @Override
   public void onServiceConnected(ComponentName name, IBinder service) {
    mMessenger = new Messenger(service);
   }
  };
 }
 
 
 
 @Override
 protected void onStart() {
  super.onStart();
  bindService(intent, conn, BIND_AUTO_CREATE);
 }
 
 
 
 @Override
 protected void onStop() {
  super.onStop();
  unbindService(conn);
 }
 
 
 
 public void onClick(View v){
  Message msg = null;
  switch (v.getId()) {
  case R.id.button1:
   msg = Message.obtain(null, 0, 0, 0);
   try {
    mMessenger.send(msg);
   } catch (RemoteException e) {
    e.printStackTrace();
   }
   break;
  case R.id.Button01:
   msg = Message.obtain(null, 1, 0, 0);
   try {
    mMessenger.send(msg);
   } catch (RemoteException e) {
    e.printStackTrace();
   }
   break;
  default:
   break;
  }
 }
}

原文链接:http://blog.csdn.net/u012702547/article/details/46989417

以上就是本文的全部内容,希望对大家学习Android软件编程有所帮助。



这篇关于Android使用Messenger实现service与activity交互的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程