我按照本教程检测网络更改,并在没有网络连接时提醒用户:
http://viralpatel.net/blogs/android-internet-connection-status-network-change/
我修改了代码,以便在用户断开网络连接时打开一个名为NoInternetConnection的活动。
当用户重新连接到网络时,我想关闭NoInternetConnection活动。我无法用广播接收器解决这个问题。关于如何做到这一点的任何提示?
这是我的广播接收器:
public class NetworkChangeReceiver extends BroadcastReceiver {
private static final String TAG = NetworkChangeReceiver.class.getSimpleName();
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Log.d(TAG, "status: " + status);
ActivityManager am = (ActivityManager) context.
getSystemService(Activity.ACTIVITY_SERVICE);
String className = am.getRunningTasks(1).get(0).topActivity.getClassName();
if(status == "connected"){
if(className.toLowerCase().contains("nointernetactivity")){
// check if the No Internet Activity context is visible
Log.d(TAG, "Close noInternetActivity");
}
}else {
if(!className.toLowerCase().contains("nointernetactivity")){
Log.d(TAG, "opening NoInternetActivity");
Intent i = new Intent(context, NoInternetActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
// Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
在我的NoInternetActivity中,我创建了一个广播接收器来关闭活动:
public class NoInternetActivity extends AppCompatActivity {
private static Context context;
private BroadcastReceiver _closeActivityReceiver = new CloseActivityReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_no_internet);
context = this;
IntentFilter filter = new IntentFilter("closeNoInternetActivity");
this.registerReceiver(_closeActivityReceiver, filter);
}
private class CloseActivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// close this damn activity!
finish();
}
}
@Override
public void onDestroy(){
super.onDestroy();
this.unregisterReceiver(this._closeActivityReceiver);
}
}
然后我在我的广播接收器中将其称为:
if(className.toLowerCase().contains("nointernetactivity")){
// check if the No Internet Activity context is visible
Log.d(TAG, "Close noInternetActivity");
Intent in = new Intent("closeNoInternetActivity");
context.sendBroadcast(in);
}