我正在尝试启动将每分钟运行一次的后台IntentService。我想在用户第一次登录我的应用程序后启动此服务,所以我的代码在这里:
此代码仅在用户登录后调用:
public class MainMenuActivity extends SingleFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
// This is reached after logging in, so we are setting alarm on login
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isOn = prefs.getBoolean(GPSTracker.PREF_IS_ALARM_ON, false);
GPSTracker.setServiceAlarm(this, true);// TODO: Always setting this to true, not sure if we should be
}
然后我在我的GPSTracker中有这个代码,它扩展了IntentService:
private static final int POLL_INTERVAL = 1000 * 60 * 1;// 1 minute
public static void setServiceAlarm(Context context, boolean isOn) {
Intent i = new Intent(context, GPSTracker.class);
PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(isOn) {
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), POLL_INTERVAL, pi);// TODO: Is AlarmManager.ELAPSED_REALTIME what I want!?
} else {
alarmManager.cancel(pi);
pi.cancel();
}
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(GPSTracker.PREF_IS_ALARM_ON, isOn).commit();
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "In onHandleIntent");
}
然而,我的onHandleIntent永远不会被调用,而且我从未在LogCat中看到任何内容。
答案 0 :(得分:4)
您正在AlarmManager.ELAPSED_REALTIME
使用System.currentTimeMillis()
。这是一个无效的组合。
或者:
将AlarmManager.RTC
与System.currentTimeMillis()
或
将AlarmManager.ELAPSED_REALTIME
与SystemClock.elapsedRealtime()