Broadcastreceiver and Paused activity

时光怂恿深爱的人放手 提交于 2019-11-28 05:28:53

When you register a broadcast receiver programatically in an activity, it will NOT get broadcasts when the activity is paused. The BroadcastReceiver docs are not as clear as they could be on this point. They recommend unregistering on onPause solely to reduce system overhead.

If you want to receive events even when your activity is not in the foreground, register the receiver in your manifest using the receiver element.

Add a Receiver to your project and you will get this event without even starting your application.

public class TestReciver extends BroadcastReceiver  {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("TestReciver",intent.getAction()+"\n"
                +intent.getDataString()+"\n"
                +"UID: "+intent.getIntExtra(Intent.EXTRA_UID,0)+"\n"
                +"DATA_REMOVED: "+intent.getBooleanExtra(Intent.EXTRA_DATA_REMOVED, false)+"\n"
                +"REPLACING: "+intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)
            );
    }

}

and in your manifest add it like this (Inside your <application> tag):

<receiver android:name="TestReciver" >
    <intent-filter >
        <action android:name="android.intent.action.PACKAGE_REMOVED" />
        <data android:scheme="package" />
    </intent-filter>
</receiver>

When you use a receiver like this you do not call any register or unregister so it will always be ready to get data.

A note is that this will not work if you let the users move your app to the SD card. If an event is sent when the SD card is unmounted the receiver will not be accessible and you will miss the event.

Maybe you can register the receiver in service which will run background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!