杀死申请后继续运行计时器

时间:2016-02-26 14:10:41

标签: java android timer

我的应用程序中有以下计时器:

public class MainScreen extends ApplicationActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
    }

    public static class ScheduleSomething extends TimerTask {
        @Override
        public void run() {
            System.out.println("This is a test!");
        }
    }
}

每秒消息“这是一次测试!”显示,但当我关闭应用程序时,它也会停止计时器。 关闭应用程序时,有没有办法让这个计时器继续运行?

我试图:

public void onStop(Bundle savedInstanceState) {
    super.onStop(savedInstanceState);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}

public void onDestroy(Bundle savedInstanceState) {
    super.onDestroy(savedInstanceState);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}

但它不起作用......

1 个答案:

答案 0 :(得分:1)

使用广播接收器在每分钟杀死应用程序后继续运行计时器:

public class TimerReceiverSyncInterval extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        scheduleAlarms(context);
        context.startService(new Intent(context, NotificationServiceSyncInterval.class));
        Log.d("TAG", "Sync OnReceive");
    }

    public static void scheduleAlarms(Context paramContext) {
        Calendar calendar = Calendar.getInstance();
        AlarmManager localAlarmManager = (AlarmManager) paramContext.getSystemService(Context.ALARM_SERVICE);
        PendingIntent localPendingIntent = PendingIntent.getService(paramContext, 0,
            new Intent(paramContext, NotificationServiceSyncInterval.class), PendingIntent.FLAG_UPDATE_CURRENT);

        localAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
               (1 * 60000), localPendingIntent);
    }
}

在下面的类中,在每分钟从TimerReceiverSyncInterval类调用的onHandleIntent方法中执行任何操作:

public class NotificationServiceSyncInterval extends IntentService {

   public NotificationServiceSyncInterval() {
       super("Tracker");
   }

   public NotificationServiceSyncInterval(String paramString) {
       super(paramString);
   }

   @Override
   protected void onHandleIntent(Intent intent) {
       //ToDo: put what you want to do here
       Log.d("TAG", "Handler call");
   }
}

在清单文件中输入一个条目:

<receiver
    android:name="com.yourpackage.TimerReceiverSyncInterval"
    android:enabled="true" >
    <intent-filter android:priority="999" >
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

<service android:name="com.yourpackage.NotificationServiceSyncInterval" />

最后从MainActivity注册广播接收器,如下所示:

TimerReceiverSyncInterval.scheduleAlarms(this);