如何在Android处于后台APP时激活广播接收器?

时间:2016-04-22 09:35:45

标签: android

我在我的应用程序中使用广播接收器,该应用程序在应用程序打开时处于活动状态,并且应用程序处于关闭状态。我想要的是仅在应用程序打开时以及特定活动时激活此广播接收器。

这是我的

public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    // Check if the application is install or uninstall and display the message accordingly
    if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
        // Application Install
        Log.e("Package Added:-", intent.getData().toString());

    } else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {

        Log.e("Package Removed:-", intent.getData().toString());
    } else if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
        Log.e("Package Replaced:-", intent.getData().toString());
    }


}

1 个答案:

答案 0 :(得分:0)

例如:

@Override
protected void onPause () {

    // Unregister since the activity is not visible
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    super.onPause();
}

@Override
protected void onResume () {
    super.onResume();

    // Register mMessageReceiver to receive messages.
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
                                                             new IntentFilter(
                                                                     YourBroadcastReceiver.class
                                                                             .getSimpleName()));
}