应用程序间的通信
来源:互联网 发布:周末是否算法定节假日 编辑:程序博客网 时间:2024/06/06 00:23
主类:
1.启动Service:
Intent startIntent = new Intent(主类.this, Service类.class);
startService(startIntent);
2.停止Service(发送广播信息给Service):
Intent stopIntent = new Intent();
stopIntent.setAction("Service类");
stopIntent.puExtra("cmd", 0);
sendBroadcast(stopIntent);
3.编写内部类,用于接收Service服务的消息:
private class DataReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
double data = intent.getDoubleExtra("data", 0);
}
}
4.重写onStart和onStop方法,添加注册和取消注册BroadcastReceicver:
protected void onStart()
{
dataReceiver = new DataReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("主类");
registerReceiver(dataReceiver, filter); /* Service服务发送消息时也会设置"主类"这个过滤条件,两边的过滤条件一致,发送的消息才能被正确接收 */
super.onStart();
}
protected void onStop()
{
unregisterReceiver(dataReceiver);
super.onStop();
}
Service类:
1.Service子类需要继续Service类
2.创建内部类,用于接收主类发来的消息(用于停止后台Service服务):
private class CommandReceiver extends BroadcastReceiver
{
@Override
public void onReceiver(Context context, Intent intent)
{
/* 主类要停止Service服务的时候,会发送一个广播消息给Service服务,值为0 */
int cmd = intent.getIntExtra("cmd", -1);
if(cmd == 0)
{
stopSelf();
}
}
}
3.重写onBind方法(这步没弄懂):
public IBinder onBind(Intent intent)
{
retun null;
}
4.重写onStartCommand方法(应该是2.1之后的SDK才加进去的方法):
public void onStartCommand(Intent intent, int flags, int startId)
{
/* 此处注册的cmdReveicer,用于接收主类发送过来的广播消息(用于停止Service服务),主类和Service类的过滤条件(“Service类”)必须相同 */
IntentFilter filter = new IntentFilter();
filter.addAction("Service类");
registerReceiver(cmdReveicer, filter); /* cmdReveicer为CommandReceiver 对象 ,在onCreate的时候创建*/
/* 发送广播消息给主类,同样,主类和Service类的过滤条件(“Service类”)必须相同 */
Intent intent = new Intent();
intent.setAction("主类");
intent.putExtra("data", 777); /* 发送数字777给主类 */
sendBroadcast(intent);
return super.onStartCommand(ntent, flags, startId);
}
5.重写onDestroy方法,在该方法中取消注册cmdReveicer
6.
- 应用程序间的通信
- Series60 2nd应用程序间的通信
- Series60 2nd应用程序间的通信
- 应用程序的通信成本
- 应用程序的通信成本
- 应用程序间通信
- 应用程序间通信
- 应用程序与DLL的通信
- 应用程序与驱动的通信
- 应用程序与驱动程序的通信
- 两个应用程序之间的通信
- 应用程序与驱动程序的通信
- 【转帖】如何建立应用程序和驱动程序间的通信
- 第四章 绑定 本机.NET应用程序间的通信
- iOS系统中应用程序间通信的方法及装置
- 应用程序之间的通信[2006-11-14]
- 一个应用程序通信的问题---SQL 触发器
- TCP/IP 应用程序的通信连接模式
- POP3与IMAP的区别和修改JBOSS的端口
- maven传递依赖的版本确定规则
- linux I2C (1)
- HBase MemstoreLAB
- 树表实现网址
- 应用程序间的通信
- oracle 11g 表空间迁移 实验过程
- linux工具rdate:同步网络时间
- 纠结的能上QQ,不能开网页问题。
- SXS: Unable to resolve storage root for assembly directory vs2010
- 日语符号 书写
- 汇编原理1:环境搭建
- 六月的工作总结
- 0704