简体   繁体   English

从活动中访问应用程序广播接收器?

[英]Access an application broadcast receiver from within an activity?

I have a broadcast set up as such in my manifest to monitor connection activity: 我在清单中设置了广播,以监视连接活动:

<application
    ... 
    <receiver
        android:name="com.blah.appname.NetworkChangeReceiver"
        android:label="NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>
    ...
</application>

Inside NetworkChangeReceiver is the onHandle() method. 在NetworkChangeReceiver内部是onHandle()方法。 This is mainly just to show a Toast message, and do some logging, and works across the entire app. 这主要是为了显示Toast消息并进行一些记录,并且可以在整个应用程序中使用。

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        // do stuff
    }

}

However, I also need to do special things in an individual activity based on the the loss of a connection. 但是,我还需要根据失去连接的情况在个别活动中做一些特殊的事情。

How can I access the onReceive() method of the existing broadcast receiver from within an activity? 如何从活动中访问现有广播接收器的onReceive()方法? I don't totally understand the internals of how the receiver is tied into the application from the manifest. 我不完全了解清单如何将接收器绑定到应用程序的内部。

You create a broadcast receiver in your app to access it in your app. 您在应用程序中创建一个广播接收器,以在您的应用程序中访问它。 The broadcast receiver in your manifest must return within 10 seconds so generally the manifest version of the broadcast receiver will just start something with an intent and then return. 清单中的广播接收器必须在10秒内返回,因此,广播接收器的清单版本通常会以某种意图开始,然后返回。

Here's a code example of adding a broadcast receiver to your app. 这是将广播接收器添加到您的应用程序的代码示例。

 BroadcastReciver yourReceiver;


 public void onStart() {
    super.onStart();
    setupGPS();
 }


private void setupGPS() {
    if (yourReceiver == null) {
        // INTENT FILTER FOR GPS MONITORING
        final IntentFilter theFilter = new IntentFilter();
        theFilter.addAction(ACTION_GPS);
        yourReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    String s = intent.getAction();
                    if (s != null) {
                        if (s.equals(ACTION_GPS)) {
                            gpsCheck();
                        }
                    }
                }
            }
        };
        getActivity().registerReceiver(yourReceiver, theFilter);
    }
    gpsCheck();
}


private void gpsCheck() {
    if (view != null) {
        LinearLayout llTrackerEnableGPS = (LinearLayout) view
                .findViewById(R.id.llTrackerEnableGPS);
        if (llTrackerEnableGPS != null) {
            LocationManager locationManager = (LocationManager) fragmentActivity
                    .getSystemService(Context.LOCATION_SERVICE);
            boolean isGPSAvailable = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            llTrackerEnableGPS.setVisibility(isGPSAvailable ? View.GONE
                    : View.VISIBLE);
        }
    }
}



@Override
public void onPause() {
    super.onPause();
    if (yourReceiver != null) {
        final FragmentActivity a = getActivity();
        if (a != null) {
            a.unregisterReceiver(yourReceiver);
        }
    }
    yourReceiver = null;
}

So you want to do something in your activity based on what you receive in the onReceive of the BroadcastReceiver? 因此,您想根据在BroadcastReceiver的onReceive中收到的内容在活动中做些什么? Here is something that I did before: 这是我之前做过的事情:

You can use LocalBroadcast . 您可以使用LocalBroadcast See LocalBroadcast Manager . 请参阅LocalBroadcast Manager For how to implement is, there is a great example on how to use LocalBroadcastManager? 对于如何实现,有一个很好的例子说明了如何使用LocalBroadcastManager? .

LocalBroadcast Manager is a helper to register for and send broadcasts of Intents to local objects within your process. LocalBroadcast Manager是一个助手,用于注册Intent广播并将其发送到流程中的本地对象。 The data you are broadcasting won't leave your app, so don't need to worry about leaking private data.` 您正在广播的数据不会离开您的应用程序,因此无需担心泄漏私人数据。

Your activity registers for this local broadcast. 您的活动注册了此本地广播。 From the NetworkChangeReceiver you send a LocalBroadcast from within the onReceive (saying that hey, I received a message. Show it activity). NetworkChangeReceiver您从onReceive内部发送了LocalBroadcast (说,嘿,我收到了一条消息。显示它的活动)。 Then inside your Activity you can listen to the broadcast. 然后在“ Activity可以收听广播。 This way if the activity is in the forefront/is active, it will receive the broadcast otherwise it won't. 这样,如果活动处于最前列/处于活动状态,它将接收广播,否则不会接收。 So, whenever you receive that local broadcast, you may do the desired action if activity is open. 因此,每当收到该本地广播时,如果活动处于打开状态,则可以执行所需的操作。

If you want to do for the whole app, then you can make all your activities extend an abstract activity. 如果您想为整个应用程序做,则可以使所有活动扩展为抽象活动。 And inside this abstract activity class you can register it for this 'LocalBroadcast'. 在这个抽象活动类中,您可以为“ LocalBroadcast”注册它。 Other way is to register for LocalBroadcast inside all your activities (but then you'll have to manage how you'll show the message only once). 另一种方法是在所有活动中注册LocalBroadcast(但随后您将不得不管理如何只显示一次消息)。 This Broadcast is private to your app. 此广播是您的应用私有的。 So its secure as well. 因此它也是安全的。

Hope it helps. 希望能帮助到你。 Same thing can be done from within the Service as well. 同样的事情也可以在Service内部完成。 This is just one of the ways to do it. 这只是做到这一点的方法之一。

You need so called dynamic broadcast receiver.You don't need to register it in the manifest file, but right inside your activity. 您需要所谓的动态广播接收器。您无需在清单文件中注册它,而只需在您的活动内部即可。

NetworkChangeReceiver mReceiver = new NetworkChangeReceiver();

@Override
protected void onStart() {
    super.onStart();
    registerReceiver(mReceiver, new IntentFilter(android.net.conn.CONNECTIVITY_CHANGE));
}

@Override
protected void onStop() {
    unregisterReceiver(mReceiver);
    super.onStop();
}

Now you can add logic into onReceive() analysing connection state and adjusting the logic. 现在,您可以将逻辑添加到onReceive()分析连接状态并调整逻辑。

Alternatively, if you want to use some libraries, then you might want to look at open source TinyBus . 另外,如果要使用某些库,则可能需要查看开源TinyBus It makes all this much simpler. 它使所有这些变得更加简单。 In your activity you need to add just this. 在您的活动中,您只需要添加此内容。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    // wire connectivity events
    TinyBus.from(this).wire(new ConnectivityEvents());

} }

@Subscribe
public void onConnectivityEvent(ConnectionChangedEvent event) {
    if (event.isConnected()) {
        // connected
    } else {
        // disconnected
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM