1
我有正在觀看數據連接更改這個簡單的廣播接收機:在整個應用程序中全局廣播和接收連接更改的最佳做法是什麼?
public class NetworkChangeReceiver extends BroadcastReceiver {
private Context mContext;
private Boolean mIsConnectedToInternet;
private enum AlarmTypes {ALARM_TYPE_REPEATED, ALARM_TYPE_UNIQUE}
@Override
public void onReceive(Context context, Intent intent) {
try {
this.mContext = context;
Logger.d("Connection changed!!!");
triggerActionBasedOnTheConnectionType(isConnectedToInternet());
} catch (Exception e) {
Logger.e("onReceive method cannot be processed");
e.printStackTrace();
}
}
public boolean isConnectedToInternet() {
mIsConnectedToInternet = false;
try {
ConnectivityManager cm =
(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
mIsConnectedToInternet = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
Logger.e("onReceive method cannot be processed");
e.printStackTrace();
}
return mIsConnectedToInternet;
}
public void triggerActionBasedOnTheConnectionType(Boolean mIsConnectedToInternet) {
try{
if(mIsConnectedToInternet == true) {
Logger.d("Device is connected");
}
if(mIsConnectedToInternet == false) {
Logger.d("Device is not connected");
}
} catch(Exception e) {
Logger.e("triggerActionBasedOnTheConnectionType method cannot be processed");
}
}
}
我想如果該設備是離線在所有視圖和全球停用所有按鈕來顯示操作欄下的一些通知欄與一些類。
我該如何以正確的方式做到這一點?有這樣的圖書館嗎?
非常感謝您的任何建議。
謝謝,但我知道如何使用它。我問如何廣播連接狀態afzer全球變化處理用戶界面的變化(停用按鈕,在操作欄下顯示消息等) – redrom
我不明白...一旦你的廣播接收機檢測到變化,你基本上調用一個函數取消激活按鈕......可能是一個靜態函數或單例類。 –
如果您有關於訪問UI元素的問題,那麼一種方法可能是在您的活動中定義您的廣播接收器。在這種情況下,您將參考您的UI元素,並且可以根據我的評論停用它們離線..或顯示通知.. –