通知网络连接的多个活动多个、通知、网络

2023-09-07 02:13:49 作者:仰泳奈何桥

我在我的Andr​​oid项目七左右的活动,并在所有7项活动,我想监视网络disconnection.I已经创建了收到通知 networkreceiver 类时,WiFi是启用或禁用。

I have around seven activities in my android project and on all seven activities, i want to monitor network disconnection.I have created a networkreceiver class which receive notification when wifi is enabled or disabled.

public class NetworkReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent arg1) {
    ConnectivityManager conMan = (ConnectivityManager) context.
        getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = conMan.getActiveNetworkInfo();
    if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) 
        Log.d("WifiReceiver", "Have Wifi Connection");
    else
        Log.d("WifiReceiver", "Don't have Wifi Connection");    
    }   
}

在清单

<receiver android:name=".NetworkReceiver" >
    <intent-filter>
         <action android:name="android.net.wifi.STATE_CHANGE" />
         <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

我的问题是,我公司自创建它作为一个独立的类,我没有得到如何获得每个WiFi是不是enable.or我要在每一个活动来创建网络接收器内部类的活动通知。

My question is , Since i created it as a seperate class, i am not getting how to get notify on every activity that wifi is not enable.or do i have to create a network receiver as inner class in every activity.

推荐答案

嗯,我认为与处理程序,答案是有点臭 - 最大的气味是,你必须保持广播接收器的实例周围 - 一个清单接收机将通过请求实例化。相反,降登记在清单和注销登记接收您的活动onSart /停止 - 无需使接收机的一个内部类。注销的onStop可能无法在升级Froyo工作,但嘿 - 我们是在奇巧

Well I think that the answer with the handlers is a bit smelly - the biggest smell being that you have to keep the instance of the broadcast receiver around - a manifest receiver at that instantiated by request. Instead drop the registration in the manifest and register unregister the receiver onSart/Stop of your activity - no need to make the receiver an inner class for that. Unregistering onStop may not work on Froyo but hey - we're on KitKat

这方式是更好的IMO你哈弗在它应该在的信号活动的接收器和接收器类不混合活性和接收器逻辑。另外,如果你设法抱到接收器的引用让我知道如何 - 我很好奇。

This way is better IMO as you haver the receiver in the activity it should signal and not mixing activity and receiver logic in the receiver class. Plus if you manage to hold a reference to the receiver let me know how - I am curious