Restrict Broadcast Receiver to application

懵懂的女人 提交于 2019-12-19 10:24:11

问题


I am working on broadcast receiver and stuck in a problem.

I am receiving a broadcast receiver in Manifest file.

<receiver class=".MyClass" android:name=".MyClass">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
    </receiver>

this is working fine and it is calling MyClass whenever there is change in connectivity.

Now the problem is whenever my application is not running still this class will receive broadcast receiver. I want it to receive whenever the application is running.

I tried it by extending BroadcastReceiver registering and unregistering broadcast in that class file and it works. But i want to achieve the same by Manifest file.

My problem will solve if it is not receiving anything when application is not opened.


回答1:


What you are talking is not possible. The whole purpose of having the intent filter in the manifest is being able to receive the intent whether or not your application is running. The only way to do what you want to is by registering/unregistering the receiver from the code [registerReceiver]




回答2:


The question was asked a long time ago but in case some one landed on this page while searching, It is possible to register and unregister broadcast receiver from code instead of doing that from manifest file. (Checking the Networking Connectivity using BroadcastReceiver in Android)




回答3:


You said "My problem will solve if it is not receiving anything when application is not opened".

Here how I understand your question and appropriate answer.

android:enabled

Whether or not the broadcast receiver can be instantiated by the system — "true" if it can be, and "false" if not. The default value is "true".

If you want to enable your receiver at runtime, you can set the state to disabled initially. You can do so in the manifest file:

<receiver
android:name=".YourReceiver"
android:enabled="false" >
<!-- your intent filter -->
</receiver>

Source: http://developer.android.com/guide/topics/manifest/receiver-element.html#enabled

http://www.grokkingandroid.com/enabling-and-disabling-broadcastreceivers/



来源:https://stackoverflow.com/questions/5725417/restrict-broadcast-receiver-to-application

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