私は、ブロードキャスト受信者のすべてのアクティビティでインターネット接続を継続的にチェックしたいと考えています。私はすでにコードを書いており、完璧に働いています。しかし、私はあらゆる活動でそれを使用したい。このコードを変更するにはどうすればよいですか?Androidインターネット接続を継続的にチェックしてください
public class MainActivity extends Activity {
private static final String LOG_TAG = "CheckNetworkStatus";
private NetworkChangeReceiver receiver;
private boolean isConnected = false;
private TextView networkStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
networkStatus = (TextView) findViewById(R.id.networkStatus);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
protected void onDestroy() {
Log.v(LOG_TAG, "onDestory");
super.onDestroy();
unregisterReceiver(receiver);
}
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if(!isConnected){
Log.v(LOG_TAG, "Now you are connected to Internet!");
networkStatus.setText("Now you are connected to Internet!");
isConnected = true;
//do your processing here ---
//if you need to post any data to the server or get status
//update from the server
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
networkStatus.setText("You are not connected to Internet!");
isConnected = false;
return false;
}
}
}
「継続的に」とはどういう意味ですか? –
Facebookはインターネット接続を同時にチェックします。 wifi/mobileを切断すると、snackbar( "Disconnect")にメッセージが表示されます。 –
これは常にチェックされません。それは何かが変化してそれに応答するときにイベントを取得します。 –