您的位置:首页 > 其它

Service、BroadcastReceiver、Activity之间的通信

2013-09-02 17:12 405 查看
Service、BroadcastReceiver、Activity三者之间可以实现相互通信,这里我们通过一个例子来看看其中的一种通信吧。
一:功能
首先应该知道,在非UI界面上操作UI是会出错的,也就是说在主线程以外的其他线程上操作主线程中的UI是违法的,但是我们可以做出如下操作,来避免这种情况的发生。
具体功能:在主界面上,启动后台服务Service,后台处理数据,前台通过BroadcastReceiver获得数据并更新UI。
二:具体实现
(1)创建继承自Service的类完成相应方法的重写,以及处理数据的操作。

public class MyService extends Service {
private Timer timer;//声明计时器
private TimerTask task;//声明计时器Task
private int index = 101;//倒计时起点变量
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startTimer();//启动计时器
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
stopTimer();//停止计时器
super.onDestroy();
}
public void startTimer() {
timer = new Timer();//实例化Timer对象
task = new TimerTask() {//实例化TimerTask
@Override
public void run() {
index--;
Intent i1 = new Intent();// 不能进行页面的跳转,只能实例化成这样
i1.setAction("action111");// 设置Intent对象的action属性,以便于在主界面做匹配
i1.putExtra("name", index);// 携带数据
sendBroadcast(i1);// 发送广播
}
};
timer.schedule(task, 1000, 1000);// 启动计时器
}
// 停止计时器
public void stopTimer() {
timer.cancel();
}
}
(2)在Minifest.xml文件中注册Service

<service android:name="MyService"></service>
(3)主界面中完成Service的启动,数据的接受,UI的更新
public class MainActivity extends Activity implements OnClickListener {
private Button startBtn, stopBtn;//声明主界面的按钮
private Intent intent;//声明Intent对象
private TextView tv;//声明主界面显示区
//创建BroadcastReceiver对象,用来接受Service发过来的消息并处理
private BroadcastReceiver receiver =new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
int num = intent.getIntExtra("name", 0);//获得后台传过来的,键值为name对应的值
tv.setText(num+"");//更新主界面UI
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到资源
startBtn = (Button) findViewById(R.id.start);
stopBtn = (Button) findViewById(R.id.stop);
//为按钮加载监听
startBtn.setOnClickListener(this);
stopBtn.setOnClickListener(this);
//找到资源
tv = (TextView) findViewById(R.id.textView1);
//动态注册BroadcastReceiver对象,并添加要接收数据的action,匹配成功处理数据,否则不处理
registerReceiver(receiver, new IntentFilter("action111"));
//实例化Intent对象
intent = new Intent(MainActivity.this, MyService.class);

}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
startService(intent);//启动Service
break;
case R.id.stop:
stopService(intent);//停止Service
break;
}
}

@Override
protected void onStop() {
unregisterReceiver(receiver);//取消动态注册
super.onStop();
}
}
(4)结果



(5)结果分析:
这里的程序主要的过程是:在Service中处理数据,然后将数据通过Intent对象,将数据传给前台,在前台通过BroadcastReceiver接收数据并更新UI。从中我们可以清晰的看到三者之间的联系与联合使用,在今后的编程中,我们可能还会用到类似的功能,大家要注意咯。



本文出自 “辛德瑞拉” 博客,请务必保留此出处http://cinderella7.blog.51cto.com/7607653/1287158
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: