service在接听电话之后失去效果
自己写的一个service,其中有一个线程,对启动的程序进行监控,若与数组中的符合,则返回主界面。实现禁用程序的目的。不接电话正常,接了电话之后就无效了。。。求解。
public class TimerService extends Service {
private ActivityManager am;
Handler handler=new Handler();
String[]selectedPackageName;
private Thread clockThread;
private int timer = 0;
private int[] a;
private boolean isRunning = true;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
public void onStart(Intent intent, int startId) {
am =(ActivityManager)getApplication().getSystemService(Context.ACTIVITY_SERVICE);
selectedPackageName= intent.getStringArrayExtra("listSelectedPackageName");
a=intent.getIntArrayExtra("theTime"); //获取传从activity递过来的数组
Log.e("TheTime", "时间是 " +a[0]*60+ "秒");
clockThread = new Thread(new Runnable() {
@Override
public void run() {
while (isRunning) {
try {
Thread.sleep(1000);
timer++;
Log.d("tag", "过去了 " +timer+ "秒");
for(int i=0;i<selectedPackageName.length;i++){
List<RunningTaskInfo> tasksInfo = am.getRunningTasks(100);
if(tasksInfo.get(0).topActivity.getPackageName().equals(selectedPackageName[i])||tasksInfo.get(0).topActivity.getPackageName().equals("com.qin.appsize")){
//返回主界面
Intent in= new Intent(Intent.ACTION_MAIN);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.addCategory(Intent.CATEGORY_HOME);
startActivity(in);
}
}
if(timer==a[0]*60){
Log.e("TheTime", "设定的时间 " +timer+ "秒到了");
isRunning=false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
clockThread.start(); /* 启动线程 */
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
} android
[解决办法]
可以用notification提高service的优先级,减小被系统回收的几率。
在Service的onCreate() or onStartCommand()方法里,调用startForeground(int id, Notification notification)。id不能为0,作用相当于NOTIFY_ID,可以用来找到这个notification,方便操作它;notification提示用户你的service在前台。
只要notification还在,你的service就能保持一个较高的优先级,不容易被系统回收。
stopForeground()可以把service设定回普通优先级。