我想在某個活動啓動時調用服務。所以,這裏的服務類:在Android中啓動服務
public class UpdaterServiceManager extends Service {
private final int UPDATE_INTERVAL = 60 * 1000;
private Timer timer = new Timer();
private static final int NOTIFICATION_EX = 1;
private NotificationManager notificationManager;
public UpdaterServiceManager() {}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// Code to execute when the service is first created
}
@Override
public void onDestroy() {
if (timer != null) {
timer.cancel();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.stat_notify_sync;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
notificationManager.notify(NOTIFICATION_EX, notification);
Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Check if there are updates here and notify if true
}
}, 0, UPDATE_INTERVAL);
return START_STICKY;
}
private void stopService() {
if (timer != null) timer.cancel();
}
}
這裏是我怎麼稱呼它:
Intent serviceIntent = new Intent();
serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager");
startService(serviceIntent);
的問題是,什麼也沒有發生。上述代碼塊在活動的onCreate
結束時被調用。我已經調試過,沒有拋出異常。
有什麼想法?
慎用定時器 - AFAIK當你的服務被關閉以釋放在服務重新啓動時,該計時器不會重新啓動。你是對的```START_STICKY```會重啓服務,但是隻有onCreate被調用,並且timer var不會被重新初始化。您可以使用START_REDELIVER_INTENT,報警服務或API 21 Job Scheduler來解決這個問題。 – georg 2015-01-12 22:24:05
如果您忘記了,請確保您已在應用程序標記內使用` `在Android清單中註冊服務。 –
2016-09-09 13:22:45