so im developing a service for a application locker. the main activity has a switch which just toggles between starting and stopping a service using startService()
and stopService()
respectively. The problem is when i try to stop the service it does not stop immediately. i have no idea how to stop it. I've even tried adding stopself()
in the onDestroy()
of my service but it doesn't work
My Code
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();
}
}
}
}
}
}