由于AlertDialog的弹出需要依赖于Activity类型的context,所以要弹出一个全局的AlertDialog(在任何界面都能弹出AlertDialog)的注意点就是获取需要弹出AlertDialog的当前的Activity.
第一步,写一个Activity的控制类,定义currentActivity代表当前Activity
public class ActivityController {
public static List<Activity> mActivityList = new ArrayList<>();
private static Activity mCurrentActivity;
public static void addActivity(Activity activity) {
mActivityList.add(activity);
}
public static void removeActivity(Activity activity) {
mActivityList.remove(activity);
}
public static void setCurrentActivity(Activity activity) {
mCurrentActivity = activity;
}
public static Activity getCurrentActivity() {
return mCurrentActivity;
}
public static void finishAll() {
for (Activity activity : mActivityList) {
if (!activity.isFinishing()) {
activity.finish();
}
}
}
}
第二步,写一个BaseActivity让所有Activity都继承它,在onCreate()中设置currentActivity
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityController.addActivity(this);
ActivityController.setCurrentActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityController.removeActivity(this);
}
}
第三步,自定义一个广播接收器,在里面弹出一个对话框,利用currentActivity作为context
public class ForceExitReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
final Activity activity = ActivityController.getCurrentActivity();
Log.d("activity", activity + "");
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle("Warning")
.setMessage("您已经被强制退出登录,请重新登录")
.setCancelable(false)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityController.finishAll();
Intent intent = new Intent(activity, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent); //重新启动LoginActivity
}
});
dialog.create().show();
}
}
第四步,在AndroidManifest.xml中注册广播
<receiver android:name=".receiver.ForceExitReceiver">
<intent-filter>
<action android:name="com.example.broadcast.FORCE_EXIT" />
</intent-filter>
</receiver>
第五步,在需要的地方发送广播
Intent intent = new Intent("com.example.broadcast.FORCE_EXIT");
sendBroadcast(intent);
这样只要在想弹出对话框的地方发送一条广播就可以弹出了。