我正在编写一个具有固定时间自动注销功能的应用程序。
这是代码:
AndroidManifest:
String expires = "2018-08-13T06:37:31Z";
SimpleDateFormat source = new SimpleDateFormat("YYYY-MM-DD'T'HH:mm:ss'Z'");
SimpleDateFormat target = new SimpleDateFormat("dd MMMMM yyyy hha");
Date expiration = source.parse(expires);
String finalDate = target.format(expiration);
System.out.println(finalDate);
活动(来自onActivityResult,成功登录后):
<application
[...]>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
[...]
<receiver
android:name="myPackage.LoginAlarm">
<intent-filter>
<action android:name="myPackage.ACTION_LOGOUT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
LoginAlarm类:
if(session.getUser().length() > 0) {
Intent i = new Intent(getResources().getString(R.string.action_logout));
i.setClass(this, LoginAlarm.class);
this.sendBroadcast(i);
al.setOwner(this); // LoginAlarm instance, setting context.
al.setAlarm(this, i);
}
如果在我的活动中我评论该行:
public class LoginAlarm extends BroadcastReceiver {
private final static long LIMIT = 600000; // session timeout, 10 minutes.
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private StartAct owner;
public LoginAlarm() {}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("LoginAlarm", "onReceive: time out.");
}
public void setAlarm(Context context, Intent intent) {
if(alarmMgr != null) alarmMgr.cancel(alarmIntent);
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmIntent = PendingIntent.getBroadcast(context, 1, intent, 0);
long trigger = System.currentTimeMillis() + LIMIT;
alarmMgr.set(AlarmManager.ELAPSED_REALTIME, trigger, alarmIntent);
String click = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(trigger));
Log.i("LoginAlarm", "setAlarm: Click at: " + click + ". Alarm set: " + end);
}
}
永远不会调用onReceive ,但是使用此行,无论LIMIT有多长,都会在设置警报后立即调用该方法。
请到目前为止,我阅读了大量文章,教程和帖子,但没有运气。
需要一些提示。
提前致谢。