Activity 如何 接收 Service的数据(Service发送数据给Activity)----非具体代码


步骤如下:

(1)定义一个Service,名为MyService 继承自 Service。在onCreate方法中声明以下语句:

Intent intent = new Intent(); //声明一个intent

intent.putExtra("key",value); //放数据

intent.setAction("action"); //添加action

(2)在需要接收数据的Activity中定义一个内部类MyReceiver继承自BroadcastReceiver

Activity{

  public class MyReceiver extends BroadcastReceiver {

    //重写onReceive方法

    public void onReceive(Bundle bundle,Intent intent){

      Bundle bundle = intent.getExtras();

      String str = bundle.getString("key"); //字符串类型的数据

      int i = bundle.getInt("key");  //整形数据

      //一些其他操作,比如更新UI

(3)在Activity的类中以及onCreate方法中作如下声明语句:

a.声明Activity的成员变量:

  private MyReciver receiver;

b.onCreate方法中启动服务:

  startService(new Intent(Activtiy.this,MyService.class));

  receiver = new MyReceiver();

  IntentFilter filter = new IntentFilter();

  filter.addAction("action"); //要与之前的action保持一致,最好以当前包名自己定义的Service的名称

  Activity.this.registerBroadcastReceiver(receiver,filter);

(4)最后不要忘记在相应的位置stopService(new Intent(Activity.this,MyService.class));