service与activity交互的方式有多种,这里说说使用Messenger来实现两者之间的交互。 Service程序: public class MessengerSe
service与activity交互的方式有多种,这里说说使用Messenger来实现两者之间的交互。
Service程序:
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:
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检测Activity或者Service是否运行的方法Android中Service和Activity相互通信示例代码Android中Service与Activity之间通信的几种方式Android Activity与Service通信(不同进程之间)详解Android Activity 与Service进行数据交互详解浅谈Android Activity与Service的交互方式Android实现Activity、Service与Broadcaster三大组件之间互相调用的方法详解Android实现从activity中停止Service的方法Android中Service实时向Activity传递数据实例分析android使用service和activity获取屏幕尺寸的方法详解Android Service与Activity之间通信的几种方式
--结束END--
本文标题: Android使用Messenger实现service与activity交互
本文链接: https://lsjlt.com/news/24865.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0