-1
我正在嘗試製作一個應用程序,用於開啓和關閉移動數據,當屏幕上的移動數據也應該打開。所以我試圖在用戶打開屏幕時停止服務。我有一個主要的活動,調用SwitchService類,有沒有什麼辦法來停止從服務本身的服務?我做了很多谷歌搜索,但沒有任何工作,onDestroy(),stopSelf().....最新的問題是什麼?停止安卓服務
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();
}
}
要停止服務中的服務,請使用stopSelf():http://developer.android.com/reference/android/app/Service.html#stopSelf()祝你的代碼在Android 5上運行,以上! http://stackoverflow.com/questions/26539445/the-setmobiledataenabled-method-is-no-longer-callable-as-of-android-l-and-later –
所以我不能開啓/關閉棒棒糖@ DanielNugent –
是的,這不會很不幸。如果你搜索,那麼關於這個問題有很多問題。除非谷歌將來爲此開放了一個合法的公共API,否則就不可能了。 –