Android 检测程序异常崩溃,重启应用

程序实时监测,程序异常   注意:Application 需在清单文件中注册

package com.catch.catchex;

import java.util.ArrayList

import com.catch.catchex.CashHandler ;
import android.app.Activity;
import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    private static Context context;
    ArrayList<Activity>    list = new ArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    /**
     * context
     */
    public static Context getContext() {
        return context;
    }

    public void init() {
        // 设置该CashHandler为程序的默认处理器
        CashHandler unCeHandler = new CashHandler(this);
        Thread.setDefaultUncaughtExceptionHandler(unCeHandler);
    }

    /**
     * @param activity activity关闭时,删除Activity列表中的Activity对象
     */
    public void removeActivity(Activity activity) {
        list.remove(activity);
    }

    /**
     * @param activity 向列表中添加Activity对象
     */
    public void addActivity(Activity activity) {
        list.add(activity);
    }

    /**
     * @param activity 关闭Activity列表中的 所有Activity
     */
    public void finishActivity() {
        for (Activity activity : list) {
            if (null != activity) {
                activity.finish();
            }
        }
        // 杀死应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}

异常处理器 CashHandler 

package com.catch.catchex;

import java.lang.Thread.UncaughtExceptionHandler;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.catch.catchex.MainActivity;
import com.catch.catchex.MyApplication;

public class CashHandler implements UncaughtExceptionHandler {

    private UncaughtExceptionHandler mDefaultHandler;
    public final String              TAG = "CatchExcep";
    MyApplication                    application;

    public CashHandler(MyApplication myApplication){
        // // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.application = myApplication;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // TODO Auto-generated method stub
        if (!handlerException(ex) && mDefaultHandler != null) {
            // 若果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                Log.e(TAG, "error ;", e);
            }
            Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
            PendingIntent restartIntent = PendingIntent.getActivity(application.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
            // 退出程序
            AlarmManager mgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒后重启
            application.finishActivity();
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     * 
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handlerException(Throwable ex) {
        // TODO Auto-generated method stub
        if (ex == null) {
            return false;
        }
        // 发个友好的提示,弹个土司
        new Thread() {

            public void run() {
                Looper.prepare();
                Toast.makeText(application.getApplicationContext(), "检测到程序异常,即将退出", Toast.LENGTH_SHORT).show();
                Looper.loop();
            };
        }.start();
        return true;
    }

}

MainActivity 中初始化

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);                         
        setContentView(R.layout.activity_main);      
        CatchExcApplication(); // 检测程序异常
        initView(); // 初始化View
                    }

 /**
     * 检测程序异常,重启
     */
    public void CatchExcApplication() {
        // 添加程序异常检测
        MyApplication application = (MyApplication) getApplication();
        application.init();
        application.addActivity(this);
    }

清单文件配置 MyApplication

 <application
        android:name="com.catch.catchex.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher_camera"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.catch.catchex.MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
捕获 Android 应用程序异常重启应用程序,可以使用 Thread.UncaughtExceptionHandler 接口。该接口用于捕获捕获异常,并在捕获异常重启应用程序。 下面是一个简单的示例代码,用于设置应用程序的 UncaughtExceptionHandler: ``` public class MyApplication extends Application implements Thread.UncaughtExceptionHandler { @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(this); } @Override public void uncaughtException(Thread thread, Throwable ex) { // 捕获异常重启应用程序 Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, pendingIntent); System.exit(2); } } ``` 在上述示例代码中,我们创建了一个自定义的 Application 类,并实现 Thread.UncaughtExceptionHandler 接口。在 onCreate() 方法中,我们将当前线程的默认 UncaughtExceptionHandler 设置为该应用程序的 UncaughtExceptionHandler。 当应用程序中有未捕获异常时,会调用 uncaughtException() 方法。在该方法中,我们创建一个 Intent 对象,用于启动 MainActivity,然后使用 PendingIntent 将该 Intent 对象封装为一个闹钟事件,并在 1 秒钟后启动该事件。最后,我们调用 System.exit() 方法退出应用程序。 这样,当应用程序中发生未捕获异常时,应用程序将自动重启

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值