この質問で提案されているように、次のコードを使用してデバイスの接続を確認しています。
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
}
私はこれを私のメインのアクティビティに持っていて、うまくいきますが、今やりたいことは、アプリケーションが起動するたびにインターネット接続をチェックすることです。再び開き、メインアクティビティを通過しないため、何もチェックされません。
この質問で示唆されているように、BroadcastReceiver を使用したインターネット アクティビティの監視に関するこのチュートリアルに従いました。noConnectivity が true の場合に AlertDialog を表示しようとしていますが、何も起こりません。
これは、上記のチュートリアルを使用した私のコードです。
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()
興奮しません。
あなたが私を助けてくれることを願っています。ありがとう