我想在用戶更改android系統時間時在首選項中存儲布爾值。因此,我加入ACTION_TIME_CHANGED到清單廣播動作:接收TIME_SET當應用程序關閉時廣播
<receiver android:name="test.TimeChangedReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
</receiver>
的TimeChangedReceiver延伸的BroadcastReceiver和覆蓋的onReceive()。在這個類中,布爾值將被存儲並顯示通知。直到應用程序被關閉
public class TimeChangedReceiver extends BroadcastReceiver {
private static final String TAG = "TimeChangedReceiver";
public TimeChangedReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
// store boolean to SharedPreferences
PreferenceUtils.getInstance().storeBoolean(true, PreferenceUtils.CHECK_LICENSE);
// build notification
int icon = android.R.drawable.ic_dialog_alert;
String title = "changed time";
String text = "user changed time";
long when = System.currentTimeMillis();
String timezone = intent.getStringExtra("time-zone");
Notification notification = new Notification(icon, title, when);
NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notification_id = (int) System.currentTimeMillis();
Intent notificationIntent = new Intent(context, MainView.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra("time-zone", timezone);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(context, title, text, contentIntent);
mgr.notify(notification_id, notification);
}
}
一切工作正常 - 在後臺不捉迷藏了。
這說:
- If you declare the BroadcastReceiver in the Manifest, it will always be active and be called even if the application is closed/stopped
- By putting your BroadcastReceiver in your Manifest, it, by default, is always active.
我怎樣才能收到反正廣播和存儲布爾?
我不需要看到通知。
嘗試在'android:name =「...」'屬性 – Marat
之後或之前在'內爲''接收器添加'android:enabled =「true」'它默認啓用^ –
@Marat [鏈接](https://developer.android.com/guide/topics/manifest/receiver-element.html) 默認值爲「true」。它沒有改變。 :( – maryBlaa