所以即时开发应用程序锁定服务。主活动有一个开关,只需分别使用startService()
和stopService()
在启动和停止服务之间切换。问题是,当我尝试停止服务时,它不会立即停止。我不知道如何阻止它。我甚至尝试在我的服务的stopself()
中添加onDestroy()
,但它不起作用
我的代码
public class LockerService extends Service {
String LockedApps[];
String allowedapp = null;
DataBaseHandler handler;
private ExecutorService executorService;
private ActivityManager activityManager = null;
String[] AppActivities = { .... };
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (executorService != null) {
executorService.shutdown();
}
stopSelf();
executorService.shutdown();
Toast.makeText(getApplicationContext(), "service stopped",
Toast.LENGTH_LONG).show();
}
@Override
public void onCreate() {
super.onCreate();
executorService = Executors.newSingleThreadExecutor();
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
LockerThread thread = new LockerThread();
executorService.submit(thread);
handler = new DataBaseHandler(this);
}
class LockerThread implements Runnable {
Intent pwdIntent = null;
public LockerThread() {
pwdIntent = new Intent(LockerService.this, Locker.class);
pwdIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@Override
public void run() {
while (true) {
handler.open();
LockedApps = handler.getPackages();
boolean status = handler.checkdata("PACKAGE");
handler.close();
while (status) {
String packname = activityManager.getRunningTasks(1).get(0).topActivity
.getPackageName();
String activityname = activityManager.getRunningTasks(1)
.get(0).topActivity.getClassName();
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(LockerService.this);
allowedapp = sp.getString("allowedapp", "anon");
// Log.i("activity name", activityname);
if ((packname.equals("com.packagename"))
&& (allowedapp.equals("com.packagename"))) {
// do nothing
} else if ((packname.equals("com.packagename"))
&& !(Arrays.asList(AppActivities)
.contains(activityname))) {
try {
Editor edit = sp.edit();
edit.putString("current_app", packname);
edit.commit();
startActivity(pwdIntent);
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ((Arrays.asList(LockedApps).contains(packname))
&& (allowedapp.equals(packname))) {
// do nothing
} else if ((Arrays.asList(LockedApps).contains(packname))) {
Editor edit = sp.edit();
edit.putString("current_app", packname);
edit.commit();
startActivity(pwdIntent);
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
答案 0 :(得分:0)
您正在停止服务但线程仍在执行..您需要停止线程..因为您有一个while(true)
循环,建议您指定一个布尔变量,该变量将设置为true on start和false on destroy和chenge the while to while(boolean_variable)