i am trying to make an app that switches the mobile data on and off , when the screen is on the mobile data should be on as well. so i was trying to stop the service when the user turns the screen on. i have a main activity that calls SwitchService class , is there any way to stop the service from inside the service itself ? i made a lot of googling but nothing worked ,, onDestroy() , stopSelf() ..... whats the problem ?
public class SwitchService extends Service {
Handler mHandler;
@Override
public void onCreate() {
}
private void switchOff() {
scheduleNext(10*1000);
setMobileDataEnabled(this,false);
}
private void switchOn() {
scheduleNext2(10*1000);
setMobileDataEnabled(this,true);
System.out.println("still runnin");
}
private void scheduleNext(int time) {
mHandler.postDelayed(new Runnable() {
public void run() {
switchOn();
}
},time);
}
private void scheduleNext2(int time) {
mHandler.postDelayed(new Runnable() {
public void run() {
switchOff();
}
},time);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandler = new android.os.Handler();
switchOn();
new Thread(new Runnable(){
@Override
public void run() {
checkLock();
}
}).start();
return START_STICKY;
}
private void checkLock() {
scheduleNextLockCheck(1*1000);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn = powerManager.isScreenOn();
if (isScreenOn) {
System.out.println("Screen onnn");
setMobileDataEnabled(this,true);
SwitchService.this.onDestroy();
}
}
private void scheduleNextLockCheck(int time) {
mHandler.postDelayed(new Runnable() {
public void run() {
checkLock();
}
},time);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
Class conmanClass;
try {
conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass
.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField
.get(conman);
final Class iConnectivityManagerClass = Class
.forName(iConnectivityManager.getClass().getName());
@SuppressWarnings("unchecked")
final Method setMobileDataEnabledMethod = iConnectivityManagerClass
.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
} catch (Exception e) {
e.printStackTrace();
}
}