在manifest文件中:
<application
android:name=".MyApp"
....
</application>
然後建立這個類來保存當前活動場景:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private static Activity mCurrentActivity = null;
public static Activity getCurrentActivity(){
return mCurrentActivity;
}
public static void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
創建新活動:
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (currActivity != null && currActivity.equals(this))
mMyApp.setCurrentActivity(null);
}
}
則:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
// i need to update activity ?????
TextView tv = (TextView)myApp.getCurrentActivity().findViewById(R.id.your_view_id);
tv.setText("Network is available");
}
}
}
發送特殊意圖的活動來更新它。但關於「更新活動」的問題非常廣泛。 – Array 2014-08-31 12:46:40
如果網絡不可用,則需要顯示沒有網絡連接。 – user3860944 2014-08-31 12:47:25
好的,你想改變顯示網絡狀態的文字嗎? – 2014-08-31 12:48:30