当我的应用程序被暂停/杀死/销毁时,倒计时器是否被停止/销毁?

时间:2015-11-03 09:37:54

标签: java android timer

我需要每天00:00重置存储在 sharedPreferences 中的值。我编写了一个进行重置的方法。到目前为止,我使用的是 countdowntimer ,当时会调用该方法。但是,如果应用程序关闭/被杀,我不知道计时器是否会继续工作。 如果没有,我该怎么办?因为我已经读过您不能使用 AlarmManager 调用方法,至少不容易。 非常感谢你给我的任何帮助。

我跳过了没有参与此操作的代码,所以你们不必阅读它。我想使用此警报,但从未调用 onRecieve 方法,因此我无法重置我需要的值。 请注意,现在警报设置为10秒进行调试。

这是警报类:

public class Twelve_Oclock_Alarm2 extends BroadcastReceiver{
private final String LOG_TAG = Twelve_Oclock_Alarm2.class.getSimpleName();

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(LOG_TAG, "OnRecieve");
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
    wl.acquire();
    Log.i(LOG_TAG, "Deberia estar reseteando el valor");
    SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.votes_key), Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(context.getString(R.string.votes_key), 1);
    editor.commit();

    wl.release();
}

public void SetAlarm(Context context){
    AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent("com.myrelease.duquep.you_matter.ACTION_EVENT_TIME");
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() +  10000, 10000 , pi);

}

}

以下是我的清单的一部分:

<receiver
        android:name=".Twelve_Oclock_Alarm2"
        android:enabled="true"
        android:process=":remote" >
        <intent-filter>
            <action android:name="com.myrelease.duquep.you_matter.ACTION_EVENT_TIME"/>
        </intent-filter>
</receiver>

这就是它被召唤的地方:

public class VoteActivity extends Activity {
    twelve_oclock_alarm2 = new Twelve_Oclock_Alarm2();
    twelve_oclock_alarm2.SetAlarm(VoteActivity.this);
}

也知道我也尝试过以这种方式实现我的意图:(并且它也没有用)

Intent i = new Intent(context, Twelve_Oclock_Alarm2.class);

我已经尝试了很多东西,但我不能让它起作用,一些帮助会很棒。

1 个答案:

答案 0 :(得分:0)

使用AlarmManager您可以在00:00(您想要的时间)通过广播,在您的接收器中,您可以重置sharedPreferences值,而不是很难做到。

有关AlarmManager的详细信息,请参阅以下内容:thisthat

Alarm Manager Example

相关问题