取消后,如何重新启动计时器?

时间:2016-08-19 16:13:52

标签: java android service timer broadcastreceiver

我有这项服务,只要所述服务也启动,它就会启动一个计时器。该想法是,如果用户手动打开屏幕(即,应用程序进入“计数器”BroadcastReceiver),则计时器被取消。否则,如果计时器自行完成,服务将自动停止(当然是通过onDestroy)。

当我想重启服务时,我的问题就出来了,没有杀死应用程序。第一。如果我只输入新的秒数并启动服务,则会收到以下错误:java.lang.IllegalStateException: Timer was canceled

我怎样摆脱上述问题?

MainService:

public class MainService extends Service {

static String BROADCAST_ACTION = "com.example.vladpintea.friendsbeforecents.displayevent";
Handler handler = new Handler();
Intent intentForStars;

String usedTimer;
long interval;

TimerTask myTask = new TimerTask() { public void run() { stopSelf(); } };
Timer myTimer = new Timer();

@Override
public void onCreate() {
    Toast.makeText(MainService.this, "Service, Created", Toast.LENGTH_SHORT).show();

    intentForStars = new Intent(BROADCAST_ACTION);

    registerReceiver(counter, new IntentFilter(Intent.ACTION_SCREEN_ON));
}

private BroadcastReceiver counter = new BroadcastReceiver() {
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onReceive(Context context, Intent intent) {
        myTimer.cancel();

        NotificationManager notify_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent_main_activity = new Intent(context, MainActivity.class);
        PendingIntent pending_intent_main_activity = PendingIntent.getActivity(context, 0,
                intent_main_activity, 0);
        Notification notification_popup = new Notification.Builder(context)
                .setContentTitle("Friends Before Cents")
                .setContentText("Oh, no! You've Lost. Try Again?")
                .setSmallIcon(R.mipmap.ic_sentiment_very_dissatisfied_white_48dp)
                .setContentIntent(pending_intent_main_activity)
                .setAutoCancel(true)
                .build();
        notify_manager.notify(0, notification_popup);

        Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
    }
};

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(MainService.this, "Service, Started", Toast.LENGTH_SHORT).show();

    try { usedTimer = intent.getStringExtra("timer"); } catch (NullPointerException ignored) {}
    try { interval = Long.parseLong(usedTimer); } catch (NumberFormatException ignored) {}
    myTimer.schedule(myTask, interval * 1000);

    handler.removeCallbacks(sendUpdatesToUI);
    handler.postDelayed(sendUpdatesToUI, 1000);

    return super.onStartCommand(intent, flags, startId);
}

private Runnable sendUpdatesToUI = new Runnable() {
    public void run() { handler.postDelayed(this, 1000); }
};

public void addStars() { sendBroadcast(intentForStars); }

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onDestroy() {
    unregisterReceiver(counter);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP
            | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
    wakeLock.acquire();

    Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);

    NotificationManager notify_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent intent_main_activity = new Intent(this.getApplicationContext(), MainActivity.class);
    PendingIntent pending_intent_main_activity = PendingIntent.getActivity(this, 0,
            intent_main_activity, 0);
    Notification notification_popup = new Notification.Builder(this)
            .setContentTitle("Friends Before Cents")
            .setContentText("Congrats! You've Won Some Coins.")
            .setSmallIcon(R.mipmap.ic_sentiment_very_satisfied_white_48dp)
            .setContentIntent(pending_intent_main_activity)
            .setAutoCancel(true)
            .build();
    notify_manager.notify(0, notification_popup);

    addStars();
}

@Override
public IBinder onBind(Intent intent) { return null; }

1 个答案:

答案 0 :(得分:0)

你不能,Doc引用说明一旦取消你就需要创建一个新实例......

Doc

  

请注意,从a的run方法中调用此方法   重复计时器任务绝对保证计时器任务将   不要再跑了。

所以基本上取消后你需要一个一个......