开机自启,需要将启动类设置成唯一项,不然自启之后,点击图标会开启新的app,点几次,开几次,但是走共同的操作,进入界面之后,退出一页需要重复多次,影响使用
<!-- 唯一栈--> <intent-filter> <action android:name="android.intent.action.SINGLE_INSTANCE_SHARE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
开机自启,通过广播的方式启动
注册广播,名字随意
<receiver android:name=".receiver.StartEnginReceiver" android:enabled="true" android:exported="true"> <intent-filter android:priority="1000"> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.ACTION_SHUTDOWN" /> </intent-filter> </receiver>
广播类
/** * 开机自动启动的广播接收器 */ public class StartEnginReceiver extends BroadcastReceiver { private static final String TAG = "StartEnginReceiver"; private static final String ACTION_SHUTDOWN = "android.intent.action.ACTION_SHUTDOWN"; public StartEnginReceiver() { } @Override public void onReceive(Context context, Intent intent) { Log.e("tag","onReceive: "+intent.getAction()); if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { Log.i(TAG, "onReceive: 我收到消息了"); Intent i = new Intent(context, StartActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } if (intent.getAction().equals(ACTION_SHUTDOWN)) { Log.i(TAG, "收到关机广播, 做关机时需要做的操作"); } } //发送串口命令 private void sendData(String text) { if (TextUtils.isEmpty(text) || text.length() % 2 != 0) { Log.e("tag","无效数据"); return; } } }
崩溃重启,在系统出错崩溃之后,自动重启,同时将错误文件保存在指定路径,路径自己选,可以上传文件或用来查看调试
public class CrashHandlerUtils implements Thread.UncaughtExceptionHandler { FaceAuth faceAuth = new FaceAuth(); public static final String TAG = "CrashHandler"; //系统默认的UncaughtException处理类 private Thread.UncaughtExceptionHandler mDefaultHandler; //CrashHandler实例 private static CrashHandlerUtils INSTANCE = new CrashHandlerUtils(); //程序的Context对象 private MyApplication mContext; //用来存储设备信息和异常信息 private Map<String, String> infos = new HashMap<String, String>(); //用于格式化日期,作为日志文件名的一部分 private DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); /** 保证只有一个CrashHandler实例 */ private CrashHandlerUtils() { } /** 获取CrashHandler实例 ,单例模式 */ public static CrashHandlerUtils getInstance() { return INSTANCE; } /** * 初始化 * * @param context */ public void init(MyApplication context) { mContext = context; //获取系统默认的UncaughtException处理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); //设置该CrashHandler为程序的默认处理器 Thread.setDefaultUncaughtExceptionHandler(this); } /** * 当UncaughtException发生时会转入该函数来处理 */ @Override public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { //如果用户没有处理则让系统默认的异常处理器来处理 mDefaultHandler.uncaughtException(thread, ex); } else { try { Thread.sleep(3000); } catch (InterruptedException e) { Log.e(TAG, "error : ", e); } // 重启 Intent in = new Intent(mContext, StartActivity.class); //FLAG_ACTIVITY_CLEAR_TASK不可省略,这个如果没有,开机自启之后,崩溃将无法重启 in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); mContext.startActivity(in); AppManager.getInstance().finishAllActivity(); android.os.Process.killProcess(android.os.Process.myPid()); //退出程序,看你们怎么写的退出,复用即可 } } /** * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. * * @param ex * @return true:如果处理了该异常信息;否则返回false. */ private boolean handleException(Throwable ex) { if (ex == null) { return false; } //使用Toast来显示异常信息 new Thread() { @Override public void run() { Looper.prepare(); ToastUtil.showShort(mContext.getResources().getString(R.string.toast_error)); Looper.loop(); } }.start(); //收集设备参数信息 collectDeviceInfo(mContext); //保存日志文件 saveCrashInfo2File(ex); return true; } /** * 收集设备参数信息 * @param ctx */ public void collectDeviceInfo(Context ctx) { try { PackageManager pm = ctx.getPackageManager(); PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); if (pi != null) { String versionName = pi.versionName == null ? "null" : pi.versionName; String versionCode = pi.versionCode + ""; infos.put("versionName", versionName); infos.put("versionCode", versionCode); } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "an error occured when collect package info", e); } Field[] fields = Build.class.getDeclaredFields(); for (Field field : fields) { try { field.setAccessible(true); infos.put(field.getName(), field.get(null).toString()); Log.d(TAG, field.getName() + " : " + field.get(null)); } catch (Exception e) { Log.e(TAG, "an error occured when collect crash info", e); } } } /** * 保存错误信息到文件中 * * @param ex * @return 返回文件名称,便于将文件传送到服务器 */ private String saveCrashInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : infos.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(key + "=" + value + "\n"); } Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.close(); String result = writer.toString(); sb.append(result); try { long timestamp = System.currentTimeMillis(); String time = formatter.format(new Date()); String deviceId = faceAuth.getDeviceId(mContext); String fileName = "applog_" +deviceId+"_"+ time ; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String paths = Environment.getExternalStorageDirectory().getAbsolutePath() + "/appConfig/errorlog"; boolean folderExists = isFolderExists(paths); if (folderExists==true){ // String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/appConfig/TostLog.txt"; String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/appConfig/errorlog/"+fileName+".txt"; File dir = new File(paths); if (!dir.exists()) { dir.mkdirs(); } FileOutputStream fos = new FileOutputStream(path ); fos.write(sb.toString().getBytes()); fos.close(); // writeSDFile(path,sb.toString()); } } return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } return null; } //文件写入 public boolean writeSDFile(String fileName, String write_str) { LogUtils.e("文件创建"); try { File file = new File(fileName); FileOutputStream fos = new FileOutputStream(file); byte[] bytes = write_str.getBytes(); fos.write(bytes); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; } //判断路径是否存在 public static boolean isFolderExists(String strFolder) { File file = new File(strFolder); if (!file.exists()) { if (file.mkdirs()) { return true; } else { return false; } } return true; } }
崩溃监控在APPlication中注册即可
//错误日志收集 CrashHandlerUtils crashHandler = CrashHandlerUtils.getInstance(); crashHandler.init(this);