大飞

大飞 关注TA

挑战一切!

大飞

大飞

关注TA

挑战一切!

  •  世界的顶端
  • 混口饭吃
  • 写了333,609字

最近回复

该文章投稿至Nemo社区   Android  板块 复制链接


Android app 被后台杀死问题

发布于 2018/01/20 22:37 1,587浏览 0回复 1,144

问题描述:

    由于Android内存管理机制,运行在后台app难免部分内存被回收,再次打开app的的时候,空指针异常,导致app崩溃,即使是微信也是难免的,有时候发现运行在后台的微信,再次打开确实重新启动了,这个做法也是值得效仿的。下面我给出比较简单的解决方案。

    1.提升应用级别,减缓被系统回收,在配置清单添加如下一句话android:persistent="true"

       

    ".MyApplication"
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/logo"
        android:supportsRtl="true"
        android:persistent="true"
        android:theme="@style/AppTheme">

    2.在application添加一个静态变量,比如status=0,在oncreate的时候改为1,在baseActivity 的onresume方法中判断是否被回收了,进行重启app

Application

 /**
     * 判断是否被后台杀死
     * @param context
     */
    public static int status=0;
    @Override
    public void onCreate() {
        super.onCreate();
        status=1;

BaseActivity

 @Override
    protected void onResume() {
        super.onResume();
        //判断是否被后台杀死
        if (MyApplication.status == 0) {
            UIUtil.restartAPP(mContext, 100);
            return;
        }

注意:status这个变量只能一次地方修改,所有的activity都继承BaseActivity

点赞(0)
点了个评