java程序崩溃怎么重启_android 异常崩溃后 重启app(进程守护方式实现)

该博客介绍了如何在Android中实现程序崩溃后自动重启,通过HeartBeatService类进行进程守护。当检测到应用未运行时,使用AppUtils.relaunchApp()方法重新启动应用,确保应用在后台或前台都能被正确重启。
摘要由CSDN通过智能技术生成

【实例简介】

【实例截图】

e7de67b664e35fdc2072591c5debdf21.png

【核心代码】

package com.sunfusheng.daemon.sample;

import android.content.ComponentName;

import android.content.Intent;

import android.os.Looper;

import android.util.Log;

import com.blankj.utilcode.util.AppUtils;

import com.sunfusheng.daemon.AbsHeartBeatService;

/**

* @author sunfusheng on 2018/8/3.

*/

public class HeartBeatService extends AbsHeartBeatService {

private static final String TAG = "---> HeartBeatService";

private static final android.os.Handler mainThreadHandler = new android.os.Handler(Looper.getMainLooper());

@Override

public void onStartService() {

Log.d(TAG, "onStartService()");

}

@Override

public void onStopService() {

Log.e(TAG, "onStopService()");

}

@Override

public long getDelayExecutedMillis() {

return 0;

}

@Override

public long getHeartBeatMillis() {

return 30 * 1000;

}

@Override

public void onHeartBeat() {

String packetName=AppUtils.getAppPackageName();

Log.d(TAG, "onHeartBeat()" packetName);

if(!AppUtils.isAppRunning(packetName)){

//方案一

AppUtils.relaunchApp();

//方案二

// Intent sayHelloIntent=new Intent(this,MainActivity.class);

// sayHelloIntent.setAction(Intent.ACTION_VIEW);

// sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

// sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

// getApplicationContext().startActivity(sayHelloIntent);

//

//方案三

// Intent intent = new Intent("android.intent.action.MAIN");

// intent.setComponent(new ComponentName(getApplicationContext().getPackageName(), MainActivity.class.getName()));

// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

// getApplicationContext().startActivity(intent);

Log.d(TAG, packetName " launchApp Sucess!!!!!!");

}else{

Log.d(TAG, packetName " is running");

if(!AppUtils.isAppForeground()){

Intent sayHelloIntent=new Intent(this,MainActivity.class);

sayHelloIntent.setAction(Intent.ACTION_VIEW);

sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

sayHelloIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

getApplicationContext().startActivity(sayHelloIntent);

Log.d(TAG, packetName " is FLAG_ACTIVITY_SINGLE_TOP!!!");

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值