我檢查設備的連接,如this question建議用下面的代碼打開:監控互聯網連接,每次應用程序在Android的
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
//notify user you are online
} else {
//notify user you are not online
}
我有這個在我的主要活動,它工作正常,但我現在想做的是每次應用程序啓動時檢查互聯網連接,有時應用程序處於某種狀態,然後互聯網斷開連接,所以當它再次打開時,它不會經過主要活動,因此不檢查任何內容。
如this question建議我遵循this tutorial與BroadcastReceiver監測互聯網活動,我試圖顯示和AlertDialog時noConnectivity是真實的,但沒有任何反應。
這是我的代碼,使用上面提到的教程:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
registerReceivers() ;
(..my activity code goes here...)
}
private void noInternet()
{
Intent myIntent = new Intent(this, NoInternetActivity.class);
startActivity(myIntent);
}
/*
* method to be invoked to register the receiver
*/
private void registerReceivers() {
registerReceiver(mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private void alert()
{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("internet connection");
alertDialog.setMessage("To use this app you need intenet connection");
alertDialog.setButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
// do application-specific task(s) based on the current network state, such
// as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
if(noConnectivity)
{
alert();
noInternet();
}
}
};
}
但無論alert()
或noInternet()
被解僱了。
希望你能幫助我。 謝謝
但我將不得不爲此在每一次活動我有嗎? – marimaf
如果您需要在每項活動中建立連接,那麼我可能會這樣做。這會很困難還是有問題? – Tim
我會說95%的活動類需要連接性,因爲他們從服務器獲取動態內容。我不覺得把這個添加到每個活動都是最好的解決方案,但如果我找不到更好的解決方案,我可能會這樣做。謝謝 – marimaf