在应用程序类中注册和取消注册广播接收器

26

我有一个广播接收器,它在Android应用程序类的onCreate()方法中注册,但如何取消注册?

例子

public class MyApplication extends Application {


@Override
public void onCreate() {
    super.onCreate();
    registerReceiver(broadcastReceiver, new IntentFilter("TIMEZONE_CHANGED"));
}
在上述代码中,我已将其注册到应用程序的onCreate()方法中,并且Application类中没有onDestroy()/onStop()方法以注销broadcastReceiver。
如何实现

2
请检查:Application.ActivityLifecycleCallbacks: 链接:https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html - Bapusaheb Shinde
5个回答

62

如果您想在应用程序运行的整个过程中监听广播,则不需要注销。根据文档(截至今天):

只要注册上下文有效,上下文注册的接收器就会接收到广播。例如,如果您在 Activity 上下文中注册,则只要该活动未被销毁,您就会接收到广播。如果您使用 Application 上下文注册,则只要应用程序正在运行,您就会接收到广播。

(https://developer.android.com/guide/components/broadcasts.html)


5
非常感谢您提供参考文献,这应该是被接受的答案。 - Hrishikesh Kadam

5

你应该创建一个BaseActivity。

示例

public class BaseActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    registerReceiver(broadcastReceiver, new IntentFilter("TIMEZONE_CHANGED"));
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(broadcastReceiver);
}
}

MainActivity继承BaseActivity。

示例:

public class MainActivity extends BaseActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
}

1
谢谢,我正在做这件事,但是每次我杀死应用程序时都会发生注销。我需要让应用程序在后台运行时仍然保持监听状态。 - Anbu
当你切换到另一个活动时,事件将再次触发,用于第二个活动。 - undefined

2
您可以在Application类中调用unregister receiver,只需像这样调用即可:

在您的MainActivity中,在onDestroy()方法内调用。
@Override
protected void onDestroy() {
    super.onDestroy();
    ((MyApplication) getApplication()).unregisterReceiver();
}

我们在您的MyApplication类中创建了unregisterReceiver()方法。
 public class MyApplication extends Application {


    @Override
    public void onCreate() {
        super.onCreate();
        registerReceiver(broadcastReceiver, new IntentFilter("TIMEZONE_CHANGED"));
    }

public void unregisterReceiver() {
     unregisterReceiver(broadcastReceiver);
}

1
这很好,但是当时区更改时,我必须在其中显示Alert Dialog,因此我需要将Activity Context传递给它,那么我该怎么做呢? - Anbu
首先,您需要更新您的问题,明确您的问题是什么。 - Mohit Suthar

-2

从您想要注销的位置调用此函数

unregisterReceiver();

-2
请在您的清单文件中使用静态注册广播接收器,这将不需要调用registerReceiver()unregisterReceiver()方法。
<receiver
   android:name=".MyTimeChangeReceiver">
   <intent-filter>
        <action android:name="android.intent.action.TIMEZONE_CHANGED" />
        <action android:name="android.intent.action.TIME_SET" />
    </intent-filter>
</receiver>

5
这在 Android API 26+ 中将无法工作:https://developer.android.com/about/versions/oreo/background.html#broadcasts - Mira_Cole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接