前些日子做的大屏android程序上线了,老是退出桌面,后面改善了app之后呢,老板不太放心,让我做个监控程序辅助监听主app是否退出桌面,现总结下这个辅助程序的相关demo:
用的不是网上广为流传的祖传代码:
public void demo1(String
packageName){
boolean isActivities=false;
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
System.out.println("topActivity="+cn.getPackageName());
if(cn.getPackageName().equals(packageName)){
isActivities=true;
}
if(!isActivities){
System.out.println("restartOtherApp");
restartOtherApp(packageName);
}
}
这段代码不知道怎么滴,加上系统签名之后有时候执行了,app关闭状态打不开,思来想去,换个方法或者将两个方法一起用,防止出现问题,下面这段是我的demo代码,用到的是利用java执行shell命令去启动程序,果不其然,至少我是百试成功了
public void demo2(){
boolean isActivities=false;
StringBuilder result = new StringBuilder();
Process process = null;
BufferedReader bufrIn = null;
BufferedReader bufrError = null;
DataOutputStream os = null;
String cmd = " /system/bin/dumpsys activity top | /system/bin/grep ACTIVITY|/system/bin/grep +项目的packageName|/system/xbin/busybox /system/xbin/wc -l ";//查询桌面上最顶端的Acitvity,查询是不是当前你的项目
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.write(cmd.getBytes(Charset.forName("utf-8")));
os.writeBytes("\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
String line = null;
while ((line = bufrIn.readLine()) != null) {
result.append(line).append('\n');
}
while ((line = bufrError.readLine()) != null) {
result.append(line).append('\n');
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bufrIn!=null){
try {
bufrIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bufrError!=null){
try {
bufrError.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (process != null) {
process.destroy();
}
}
result=1的时候就是你的程序在桌面上啦,不等于1的时候表示你的程序不在桌面上了
就是这个样子啦
本人小白一枚,欢迎大神们指正,不剩感激,(* ̄︶ ̄)