Android程序监听已知包名的APK是否运行

来源:互联网 时间:1970-01-01

最新项目中用到了自己的客户端要监听在自己客户端里下载的APK是否在运行,整理下基本实现代码


我是用定时器调用个BroadcastReceiver来实现


BroadcastReceiver类中自己重写onReceive方法就可以了


public class Tools {

private static long time = 10*1000;//定时器频率
private static String pck;
private static long totalTime;
private static long percentTime;
// 发送定时广播 服务器传时间单位秒
public static void setSchedule(Context context,String pack,int totaltimes) {
pck = pack;
totalTime = totaltimes*1000;
percentTime = 0;
Intent intent = new Intent(context, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
long firstime = SystemClock.elapsedRealtime();// 开始时间
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,
time, sender);// 10秒一个周期,不停的发送广播
}


// 取消定时器
public static void cancleSchedule(Context context) {
Intent intent = new Intent(context, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(sender);
}
//判断监听已知包名的程序是否运行
public static void getinfoisrunning(Context context) {
ActivityManager mActivityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> listOfProcesses = mActivityManager
.getRunningAppProcesses();

for (ActivityManager.RunningAppProcessInfo process : listOfProcesses) {
Log.e("Process Running", process.processName);
if (process.processName.contains(pck)) {
System.out.println("正在运行");
Toast.makeText(context, "正在运行程序", Toast.LENGTH_SHORT).show();
if(percentTime == totalTime){
System.out.println("获得奖励...............");
}
percentTime = percentTime + time;
break;
}

System.out.println("percentTime==="+percentTime);
System.out.println("time===="+time);
if(percentTime>=time){
System.out.println("停止运行取消奖励...........");
cancleSchedule(context);
percentTime = 0;
break;
}
}
percentTime = percentTime + time;
}

}


相关阅读:
Top