我正在使用服务从JSON API下载一些数据。但是我试图阻止它的方式实际上并没有真正发挥作用,而且我不确定为什么。以下是MyService.class
中的内容:
public class MyService extends Service{
Thread myThread;
Handler myHandler = new Handler();
public static boolean state = false;
PowerManager.WakeLock wl ;
PowerManager pm;
boolean wakeUpFlag = false;
public class LocalBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public Runnable myRunnableProgress = new Runnable() {
public void run() {
state = false;
stopSelf();
if(wakeUpFlag){
wl.release();
System.out.println("Released the wakelock");
}
}
};
@Override
public void onCreate(){
if (RPCCommunicator.chkNetworkStatus()) {
myThread = new Thread(new Runnable() {
public void run() {
downloadGenres();
downloadCollections();
downloadTutorials();
downloadNotices();
myHandler.post(myRunnableProgress);
}
});
myThread.start();
}
}
@Override
public void onDestroy(){
super.onDestroy();
Intent intent = new Intent("finish");
this.sendBroadcast(intent);
}
@Override
public void onStart(Intent intent, int startid) {
super.onStart(intent, startid);
wakeUpFlag = false;
pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
if(pm.isScreenOn()) {
wakeUpFlag = true;
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"boom");
Log.e("","Screen off - wake lock acquired");
wl.acquire();
}
else{
Log.e("","Screen on - no need of wake lock");
}
}
//Download genres
public void downloadGenres(){
JsonGenre jsonGenres = new JsonGenre();
jsonGenres.executeInsert(this);
}
//Download collections
public void downloadCollections(){
JsonCollection jsonColl = new JsonCollection();
jsonColl.executeInsert(MyService.this);
}
//Download tutorial
public void downloadTutorials(){
JsonContent jsonContent = new JsonContent();
jsonContent.executeInsert(this);
}
//Download Notices
public void downloadNotices(){
JsonNews jsonNews = new JsonNews();
jsonNews.executeInsert(this);
}
}
以下是我在我的活动(onClickListener
)中启动服务的方式:
getApplicationContext().startService(new Intent(MyCollectionList.this,MyService.class));
有什么建议吗?