【原创】Service监听到事件后关闭启动自己的Activity

来源:互联网 发布:淘宝追加评论规则 编辑:程序博客网 时间:2024/05/16 23:35

今天写代码的时候,遇到一个小问题,逻辑过程如下:

1 在mActivity中启动一个mService;

2 mActivity负责通知用户信息,运行在前台;

3 mService负责监听手机摇晃事件,运行在后台;

4 当mService监听到摇晃事件后,关闭启动mService的mActivity。

 

了解了逻辑过程后,给出如下思路:

思路1:在mService中获取mActivity的实例m,当需要关闭mActivity时,直接执行m.finish(),关闭mActivity。

在根据思路1编写程序的过程中,遇到了一个严重的问题,我在mService中无法获得mActivity的实例m。(PS:是我获取不到,不代表别人获取不到,换句话说,是我太菜了……)具体代码见我的上上篇博文。

思路2:当监听到手机摇晃事件后,在mService向mActivity发送带有特定action的广播,前提是在mActivity设置好广播监听器BroadCastReceiver。当mActivity接收到广播后,判断一下是否是对应的action,如果是,关闭自己(mActivity.this.finifh();)如果不是,啥也不做。部分代码如下:

mService中,关键位置添加以下代码:

    指定广播目标Action:Intent intent = new Intent(actionString);

  并且可通过Intent携带消息 :intent.putExtra("msg", "hi,我通过广播发送消息了");

  发送广播消息:Context.sendBroadcast(intent );

 

在mActivity中,添加以下代码:

UpdateReceiver receiver;

 

public class UpdateReceiver extends BroadcastReceiver {

 

     public void onReceive(Context context, Intent intent) {

     Log.e("sendBroadcast","receive");

     boolean close = intent.getBooleanExtra("CLOSE", false);

     if (close)

     NoticeActivity.this.finish();

     }

}

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

 

//监听广播,获得service传过来的参数,判断是否关闭本activity

receiver = new UpdateReceiver();

IntentFilter filter = new IntentFilter();

filter.addAction("com.iqiwu.sendMsg");

this.registerReceiver(receiver, filter);

}

0 0