android应用程序遇到程序关闭后重启的问题

 

程序退出的情况:

1、程序异常退出,需要程序重启

2、程序退出,在没有异常报出,或第三库问题引起

 

1、程序异常退出,需要程序重启

 

第一步:一个类继承UncaughtExceptionHandler,并将错误信息保存到sd卡

 

public class MyExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler,
		ConstantDividerDao {

	private static final String TAG = "MyExceptionHandler";
	private static final boolean D = true;
	
	private final Context myContext;

	public MyExceptionHandler(Context context, Class<?> c) {
		myContext = context;
	}

	public void uncaughtException(Thread thread, Throwable exception) {

		Log.e(TAG, "+++ uncaughtException +++");

		for (int i = 0; i < recordingDidList.size(); i++) {
			String did = recordingDidList.get(i);
			if (recordingDidList.contains(did) || warningDidList.contains(did)) {
				StopCameraRecordUtil.stopCameraRecord(myContext, did);
			}
		}

		Toast.makeText(myContext, myContext.getString(R.string.rebootTip),
				Toast.LENGTH_SHORT).show();

		StringWriter stackTrace = new StringWriter();
		exception.printStackTrace(new PrintWriter(stackTrace));
		System.err.println(stackTrace);// You can use LogCat too
		String s = stackTrace.toString();
		System.out.println(stackTrace.toString());

		getFileFromBytes(s);

		Intent mStartActivity = new Intent(myContext, StartActivity.class);
		int mPendingIntentId = 123456;
		PendingIntent mPendingIntent = PendingIntent.getActivity(myContext,
				mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager mgr = (AlarmManager) myContext
				.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, mPendingIntent);

		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}

	/**
	 * 将String数据存为文件, 路径可自行定义Constant.UPDATEPATH
	 */
	public static File getFileFromBytes(String name) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		name = name + "/n" + df.format(new Date());

		String path = Constant.UPDATEPATH;
		byte[] b = name.getBytes();
		BufferedOutputStream stream = null;
		GrandAuth.grandAuth(path);
		File file = new File(path);
		try {
			FileOutputStream fstream = new FileOutputStream(file + "/log.txt", true);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}
}


 

第二步: 在可能遇到错误信息的Activity的OnCreate方法增加

	// 遇到异常重新启动程序
		Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
				MainActivity.class));


 

2、程序退出,在没有异常报出,或第三库问题引起

 

第一步: 定义一个工具类,查询当前应用程序是不是在运行状态

 

public class ServiceOrRunningUtil {
	
	private static final String TAG = "ServiceOrRunningUtil";
	
	public static boolean isAppStarted(Context context, String PackageName) {
		boolean isAppRunning = false;
		
		ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> list = am.getRunningTasks(100);
	    for (RunningTaskInfo info : list) {
	        if (info.topActivity.getPackageName().equals(PackageName) && info.baseActivity.getPackageName().equals(PackageName)) {
	       // 	Log.d(TAG, "info:" + info.topActivity.G)
	            isAppRunning = true;
	            break;
	        }
	    }
		return isAppRunning;
	}
}


第二步:写一个广播启动程序, AndroidManifest.xml注册  <receiver android:name="object.nvs.receiver.RebootSystemReceiver" >
        </receiver>

 

public class RebootSystemReceiver extends BroadcastReceiver {

	private static final String TAG = "RebootSystemReceiver";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		//根据包名查找计算机后台运行程序是不是启动
		boolean isStart = ServiceOrRunningUtil.isAppStarted(context, "object.nvs.client");
		Log.d(TAG, "isStart: " + isStart);
		if (!isStart) {
			Intent newIntent = new Intent(context, StartActivity.class);
			newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 注意,必须添加这个标记,否则启动会失败
			context.startActivity(newIntent);
		}
	}
}


 

 

第三步: 启动一个闹钟定义查询, 下面3000 说明的是3秒后查询一次

 

	// 指定要启动的Service组件
		Intent intent = new Intent(BridgeService.this,
				RebootSystemReceiver.class);
		// 创建PendingIntent对象
		final PendingIntent mAlarmSender = PendingIntent.getBroadcast(BridgeService.this,
				1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		// Schedule the alarm!
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0,
				3000, mAlarmSender); 


 

以上实现的所有代码。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值