【问题标题】:Unregister Receiver is it necessary?有必要注销Receiver吗?
【发布时间】:2015-02-19 18:31:02
【问题描述】:

我有一个警报管理器,我已在我的代码中注册了它的接收器。在Timer 的情况下拥有警报管理器的全部意义在于它应该在处于暂停状态时在后台运行。现在,我是在onPause() 还是OnDestroy() 中注销它,它仍然会在后台运行并唤醒并且接收者会收到它吗?

编辑:

   @Override
    public void onReceive(Context context, Intent intent) {
    Intent i = new Intent(context, MyClass.class);
    i.putExtra("fromReciever", true);
    startActivity(i);

    }

【问题讨论】:

    标签: android receiver


    【解决方案1】:

    我建议您在AndroidManifest.xml 文件中注册它。示例:

    <receiver android:name="com.example.android.MyReceiver" >
        <intent-filter>
            <action android:name="com.example.android.USER_ACTION" />
        </intent-filter>
    </receiver>
    

    只要您的设备上安装了应用程序,这将使您的接收器保持注册状态。您所要做的就是实现它:

    public class MyReceiver extends BroadcastReceiver {
    
       @Override
       public void onReceive(Context context, Intent intent) {
          Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
       }
    
    }
    

    你已经准备好了。

    此外,您可以查看this tutorial 了解更多信息。

    已添加

    如果您想恢复您的Activity,您可以在您的Receiver onReceive 方法中添加此代码。

    Intent intent = new Intent(this, YourActivity.class);
    intent.putExtra("fromOnReceive", true);
    context.startActivity(intent);
    

    然后,在您的 Activity onCreate 方法中,检查它是否是从您的 Receiver 调用的

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(getIntent().hasExtras()){
            boolean fromReceiver = getIntent().getExtras().getBoolean("fromOnReceive");
            if(fromReceiver)
                //Do work 
        }
    }
    

    【讨论】:

    • 但是醒来后我希望它在那个正在运行许多事情的 Activity 中做一些事情。基本上它运行我的状态机。
    • 您可以通过启动意图轻松启动该活动。我将更新我的答案并添加所需的代码。 @JourneyWithAndroid
    • 是的,对不起,这是我的错。您必须在您的 broadcastReceiver onReceive 方法中调用 startActivity(),如下所示:context.startActivity(intent); 查看我的更新答案。 @JourneyWithAndroid
    • @JourneyWithAndroid :-) 编码愉快!
    • @JourneyWithAndroid 你可以选择你喜欢的,我只是提供了一个例子。
    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2016-10-03
    • 2012-12-14
    相关资源
    最近更新 更多