我正在开发一个需要永久互联网连接的应用程序。如果没有互联网连接,我希望用户退出应用程序(进入登录屏幕)。我有一个检测网络连接的网络接收器类。我希望这个类要么终止堆栈顶部的活动,要么开始一个新的登录活动并删除整个历史堆栈。
问题是我无法从接收器类内部完成前台活动,并且无法知道当网络出现故障时用户处于哪个活动中。如果我从这个类开始一个新的登录活动,当用户按下“返回”时,他会被带回应用程序(如果他重新连接到网络),但应用程序没有登录并崩溃。
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK || FLAG_ACTIVITY_CLEAR_TOP);
从我的 NetworkStateReceiver 类开始新的登录活动时尝试使用。但它不起作用,据我了解,这会创建一个新任务,其中唯一的活动是我开始的活动(登录),但所有其他活动的旧任务保持不变。
所以我需要:
- 一种完成班级前台活动的方法
- 或一种从类开始新活动并清空活动堆栈的方法
这是它的价值的接收器代码:
public class NetworkStateReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
// super.onReceive(context, intent);
Log.d("app","Network connectivity change");
if(intent.getExtras()!=null) {
Login.apiKey = null;
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
Log.i("app","Network "+ni.getTypeName()+" connected");
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE) && !Login.loginActive) {
Log.d("app","There's no network connectivity");
Toast.makeText(context, "No internet connection. Logging out", Toast.LENGTH_LONG).show();
//logout
Receiver.engine(context).halt();
Receiver.mSipdroidEngine = null;
Receiver.reRegister(0);
new Thread(ChatList.runnable).interrupt();
ChatList.buddyList.clear();
Login.apiKey = null;
Log.i("Logout", "Logged out!");
Login.loggedOut = true;
Intent myIntent = new Intent(context, Login.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// myIntent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
context.startActivity(myIntent);
}
}
}
解决方案: 将所有活动的引用传递给接收者
//random user_activity
@Override
protected void onPause() {
super.onPause();
NetworkStateReceiver.curActivity = null;
}
@Override
protected void onResume() {
super.onResume();
NetworkStateReceiver.curActivity = user_activity.this; //edited : getParent() doesn't always work
}
在网络接收器中onReceive()
:
if(curActivity != null)
{
curActivity.finish();
}