使用BroadcastReceiver实现Android进入后台预定时间后退出所有Activity,进入登录界面

6D9EA836C3ECE2234C1014F404730D1E.jpg
前言

我们有些项目出于安全考虑(或者登录失效),在App进入后台一定时间后需要退出App(或者进入登入、其他身份验证界面),这个功能iOS很好实现。Android因为activity以栈的形式存放,且不像iOS那样释放界面。所以在进入登录界面时需要finish所有activity

方法
  • System.exit(0)
    可惜无法再次启动新界面
  • 根据Activity的声明周期
    我们知道Android的窗口类提供了历史栈,我们可以通过stack的原理来巧妙的实现,这里我们在A窗口打开B窗口时在Intent中直接加入标 志 Intent.FLAG_ACTIVITY_CLEAR_TOP,这样开启B时将会清除该进程空间的所有Activity。
//在A窗口中使用下面的代码调用B窗口
Intent intent = new Intent(); 
intent.setClass(this, Activity.class); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置 
startActivity(intent);
  • 任务管理器方法
    首先要说明该方法运行在Android 1.5 API Level为3以上才可以,同时需要权限
  

系统会将该包下的所有进程、服务全部杀掉,就可以杀干净了

  ActivityManager am =(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
  am.restartPackage(getPackageName()); 
  • BroadcastReceiver使用广播将所有activity进行finish
新建TBaseActivity
public class TBaseActivity extends AppCompatActivity {

    private boolean isAppForeground() {
        ActivityManager manager = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
        List info = manager.getRunningAppProcesses();
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningAppProcessInfo aInfo : info) {
            if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName.equals(Utils.getApp().getPackageName());
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("MyTest",this.getClass().toString() + " onDestroy");
        if (exitAppHandler != null) {
            exitAppHandler.removeCallbacksAndMessages(null);
            exitAppHandler = null;
        }
        if (screenListener != null) {
            screenListener.unregisterListener();
            screenListener = null;
        }
        if (myBaseActiviyBroadcastReceiver != null) {
            unregisterReceiver(myBaseActiviyBroadcastReceiver);
            myBaseActiviyBroadcastReceiver = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (!isAppForeground()) {
            // app 进入后台
            Log.d("MyTest", "-------------进入后台------->");
            exitAppDelayTime();
        } else {

        }
    }

    private Handler exitAppHandler;
    private void exitAppDelayTime() {
        if (exitAppHandler != null) {
            exitAppHandler.removeCallbacksAndMessages(null);
            exitAppHandler = null;
        }
        exitAppHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.d("MyTest", "------------- ExitAPP ------->");
                //AppUtils.exitApp();
                exitAllActivityAndGotoLoginActivity();
            }
        };
        exitAppHandler.sendEmptyMessageDelayed(0, 300 * 1000);//300秒退出APP
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.getClass() != PwdLoginActivity.class && this.getClass() != LaunchActivity.class && this.getClass() != TouchLoginActivity.class) {
            //当不在启动页 密码登录 手势登录时
            if (UserManager.getInstance().userInfoModel == null) {//当清空手机内存时(如:使用360等手机卫士清空手机内存)

                //
                exitAllActivityAndGotoLoginActivity();
            }
        }

    }

    private void exitAllActivityAndGotoLoginActivity() {
        Intent intent1 = new Intent(this, PwdLoginActivity.class);
        startActivity(intent1);
        //
        Intent intent = new Intent("drc.xxx.yyy.baseActivity");
        intent.putExtra("closeAll", 1);
        sendBroadcast(intent);//发送广播
    }

    private ScreenListener screenListener;
    private void setScreenListener() {

        screenListener = new ScreenListener(this);
        screenListener.begin(new ScreenListener.ScreenStateListener() {

            @Override
            public void onUserPresent() {//解锁
                Log.e("onUserPresent", "onUserPresent");
            }

            @Override
            public void onScreenOn() {//开屏
                Log.e("onScreenOn", "onScreenOn");
            }

            @Override
            public void onScreenOff() {//锁屏
                Log.e("onScreenOff", "onScreenOff");
                exitAppDelayTime();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏

        super.onCreate(savedInstanceState);

        setScreenListener();

        registerBroadcast();

    }

    //////////////////

    private MyBaseActiviyBroadcastReceiver myBaseActiviyBroadcastReceiver;
    private void registerBroadcast() {
        //动态注册广播
        myBaseActiviyBroadcastReceiver = new MyBaseActiviyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter("drc.xxx.yyy.baseActivity");
        registerReceiver(myBaseActiviyBroadcastReceiver, intentFilter);
    }

    //定义一个广播
    public class MyBaseActiviyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //接收发送过来的广播内容
            int closeAll = intent.getIntExtra("closeAll", 0);
            if (closeAll == 1) {
                finish();//销毁BaseActivity
            }
        }
    }
}
ScreenListener 屏幕锁屏相关监听类
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.PowerManager;

/**
 * Created by tikeyc on 2017/11/23.
 * GitHub:https://github.com/tikeyc
 */

public class ScreenListener {

    private Context mContext;
    private ScreenBroadcastReceiver mScreenReceiver;
    private ScreenStateListener mScreenStateListener;

    public ScreenListener(Context context) {
        mContext = context;
        mScreenReceiver = new ScreenBroadcastReceiver();
    }

    /**
     * screen状态广播接收者
     */
    private class ScreenBroadcastReceiver extends BroadcastReceiver {
        private String action = null;

        @Override
        public void onReceive(Context context, Intent intent) {
            action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) { // 开屏
                mScreenStateListener.onScreenOn();
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 锁屏
                mScreenStateListener.onScreenOff();
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) { // 解锁
                mScreenStateListener.onUserPresent();
            }
        }
    }

    /**
     * 开始监听screen状态
     *
     * @param listener
     */
    public void begin(ScreenStateListener listener) {
        mScreenStateListener = listener;
        registerListener();
        getScreenState();
    }

    /**
     * 获取screen状态
     */
    private void getScreenState() {
        PowerManager manager = (PowerManager) mContext
                .getSystemService(Context.POWER_SERVICE);
        if (manager.isScreenOn()) {
            if (mScreenStateListener != null) {
                mScreenStateListener.onScreenOn();
            }
        } else {
            if (mScreenStateListener != null) {
                mScreenStateListener.onScreenOff();
            }
        }
    }

    /**
     * 停止screen状态监听
     */
    public void unregisterListener() {
        mContext.unregisterReceiver(mScreenReceiver);
    }

    /**
     * 启动screen状态广播接收器
     */
    private void registerListener() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        mContext.registerReceiver(mScreenReceiver, filter);
    }

    public interface ScreenStateListener {// 返回给调用者屏幕状态信息
        public void onScreenOn();

        public void onScreenOff();

        public void onUserPresent();
    }

}

你可能感兴趣的:(使用BroadcastReceiver实现Android进入后台预定时间后退出所有Activity,进入登录界面)