我在Android服务中遇到计时器问题。 所以我已经为计时器设置了公共静态,在销毁时我正在取消并清除计时器。
我面临的问题是2个计时器中只有1个不停止,我无法弄清楚原因。
这是代码的一部分:
private static Timer t,t1; @Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d("Test Service","Service desroyed");
//Toast.makeText(getApplicationContext(), "Service Destroy",1).show();
sendMessage("Stop Audio");
t.cancel();
t.purge();
t1.cancel();
t1.purge();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t1 = new Timer();
if(PackageManager.PERMISSION_GRANTED == pm.checkPermission(Manifest.permission.RECORD_AUDIO,foregroundappPackageInfo.packageName)){
final int interval = 15000; // 15 Second
t1.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Boolean temp = validateMicAvailability();
if(temp) {
isStarted = true;
sendMessage("Start Audio");
t1.cancel();
t1.purge();
}else{
if(isStarted) {
t1.cancel();
t1.purge();
}
}
}
},30000,interval);
}else {
isStarted=true;
sendMessage("Start Audio");
final int interval = 2000; // 2 Second
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
ActivityManager am = (ActivityManager) TestService.this.getSystemService(ACTIVITY_SERVICE);
ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
PackageManager pm = TestService.this.getPackageManager();
PackageInfo foregroundappPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundappPackageInfo.applicationInfo.loadLabel(pm).toString();
if(Build.VERSION.SDK_INT >= 22 ) {
if (PackageManager.PERMISSION_GRANTED == pm.checkPermission(Manifest.permission.RECORD_AUDIO, getForegroundApp().replaceAll("\u0000",""))) {
Log.d("Test Service", "Stoping audio if audio permision app in front API22");
if (isStarted) {
isStarted = false;
sendMessage("Stop Audio");
}
} else {
if (!isStarted) {
isStarted = true;
sendMessage("Start Audio");
}
}
}else{
if (PackageManager.PERMISSION_GRANTED == pm.checkPermission(Manifest.permission.RECORD_AUDIO, foregroundappPackageInfo.packageName)) {
if (foregroundTaskAppName == "ALLeVIEW SCAN") {
Log.d(TAG, "HERE IF ALLEVIEW IS IN FRONT");
t.cancel();
t.purge();
} else {
Log.d("Test Service", "Stoping audio if audio permision app in front API <22");
if (isStarted) {
isStarted = false;
sendMessage("Stop Audio");
}
}
} else {
if (!isStarted) {
isStarted = true;
sendMessage("Start Audio");
}
}
}
}catch(Exception e){};
}
},0,interval);
}
}catch(Exception e){};
//Toast.makeText(getApplicationContext(), "Service Working", 1).show();
return super.onStartCommand(intent, flags, startId);
}
所以计时器t1,我很难阻止它。当我调试应用程序时,我看到它正在执行t1.cancel()和t1.purge(),但是计时器继续运行,我可以看到日志显示Log.d(TAG,“音频仍然接听来电”) ;我看到开始是真的。此外,当服务从我的主要活动中销毁时,计时器t1也不会取消。
我也试过设置t1 = null,但这也没有帮助。
我从主活动中的onPause方法启动服务,并取消主活动中的onResume服务。
任何想法尝试什么?为什么t1计时器不想停止?当服务被销毁时,计时器t停止,这是停止计时器t的唯一方法。
提前感谢您提供任何帮助