背景:Android开发中各个组件需要相互传递数据,我们一个Activity发送指令到服务,服务执行任务之后将数据返回给Activity我们可以用EventBus,也可以用Binder,我们也可以使用广播,当然方法不止这几种,这里我们选择广播来演示下数据的接收。
一。Avtivity
public class MainActivity extends Activity {
private Intent mintent;
private TextView mtv;
private Button stopb;
private MyReceiver receiverTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mtv = (TextView)findViewById(R.id.tv_show);
stopb = (Button)findViewById(R.id.btn_stop);
//注册广播接受者
receiverTest = new MyReceiver();
IntentFilter inf = new IntentFilter("com.hlhjni.monisend.MainActivity");
registerReceiver(receiverTest,inf);
//开启服务
if(mintent == null) mintent = new Intent(this,MyService.class);
startService(mintent);
}
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
String count = bundle.getString("count");
mtv.setText(count+"\n");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiverTest);
}
}
二。Services
private MainActivity hh;
private int count;
private Timer mtimer;
@Override
public void onCreate() {
//执行服务任务
mtimer = new Timer();
mtimer.schedule(new TimerTask() {
@Override
public void run() {
if(count ==5000 ){ count =0;mtimer.cancel();}
count++;
//发送广播
Intent intent=new Intent();
intent.putExtra("count", count+"");
intent.setAction("com.hlhjni.monisend.MainActivity");
sendBroadcast(intent);
}
},100,100);
}