我自己写的一个class(没有继承任何class) 现在想在这个class传数据给Activity或者Service 有什么好方法,因为现在我拿不到Activity或者Service的对象 |
使用观察着模式:普通class 继承 Observable, Activity 或 service 实现接口Observer
Activity与Service交互之Broadcast Receiver篇
Activity与Service之间的通信除了IBinder,还可以用Broadcast Receiver。
案例:通过service向远程服务器发送请求,根据服务器返回的结果动态更新主程序UI界面,主程序可实时关闭或重启服务。
在主程序activity中注册一个BroadcastReceiver,用于接收Service发布的广播。
- @Override
- protected void onStart() {//重写onStart方法
- dataReceiver = new DataReceiver();
- IntentFilter filter = new IntentFilter();//创建IntentFilter对象
- filter.addAction("your.action");
- registerReceiver(dataReceiver, filter);//注册Broadcast Receiver
- super.onStart();
- }
主程序activity可发布广播,用于向后台service传递数据或控制信息,如停止service命令。
- btnStop.setOnClickListener(new OnClickListener() {//为按钮添加点击事件监听
- @Override
- public void onClick(View v) {//重写onClick方法
- Intent myIntent = new Intent();//创建Intent对象
- myIntent.setAction("your.action");
- myIntent.putExtra("cmd", CMD_STOP_SERVICE);
- sendBroadcast(myIntent);//发送广播
- }
- });
后台service注册BroadCastReceiver用于接受主程序发送的广播
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {//重写onStartCommand方法
- IntentFilter filter = new IntentFilter();//创建IntentFilter对象
- filter.addAction("your.action");
- registerReceiver(cmdReceiver, filter);//注册Broadcast Receiver
- doJob();//调用方法启动线程,自己来完成
- return super.onStartCommand(intent, flags, startId);
- }
后台service向主程序实时发送广播。
- Object data;//服务器返回的数据data
- Intent intent = new Intent();//创建Intent对象
- intent.setAction("com.justel.service");
- intent.putExtra("data", data);
- sendBroadcast(intent);//发送广播
这样就剥离了Activity与Service之间相互的依赖
Activity与Service通过广播交换复杂对象数据用法详解
最近学习新浪微博开放平台,实现了一个应用,通过后台Service监控微博数据,发现数据更新后通知前台程序,并将博客数据列表发送给前台Activity。
其中利用BroadcastReceiver对象分别在Activity和Service注册了一个广播,通过发送不同的广播控制前台和后台的数据交换,并通过Serializable对象传递复杂的自定义对象类型给Activity。
程序片段如下:后台监控weibo Service
- //继承自Service的子类
复制代码
AndriodFocusMe 主UI界面Activity
- public class AndriodFocusMe extends Activity implements Runnable{
- /** Called when the activity is first created. */
- DataReceiver dataReceiver;//BroadcastReceiver对象
- ProgressBar progressbar;
- ListView listview;
- int CMD_STOP_SERVICE = 0;
- int CMD_RESET_SERVICE = 1;
- int CMD_GET_WEIBO_DATA = 2;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.weibodataview);
- Button beginOuathBtn= (Button) findViewById(R.id.Button_WeiBo);
- Button endBtn = (Button) findViewById(R.id.flashData);
- listview = (ListView)findViewById(R.id.weibodatalist);
- progressbar = (ProgressBar)findViewById(R.id.wbprogressbar);
- progressbar.setVisibility(View.INVISIBLE);
- beginOuathBtn.setOnClickListener(new Button.OnClickListener()
- {
- ………………………………………………………………
- …………………………