Android Custom-Time 通知 Service/Broadcast/AlarmManager
Android Custom-Time Notification Service/Broadcast/AlarmManager
我的目标是实现在一天中的 user-chosen 时间出现的通知。
我已经尝试过 Service
,这可行,但问题是它需要大量后台进程(代码在下面),另一个是 AlarmManager
但这似乎无法正常工作,尤其是 API 19+。我在 Whosebug 上找不到 up-to-date well-coded 教程或类似问题的有用答案,所以我求助于您。
你们都知道:如果朋友向您发送 Whatsapp 短信,即使您的 phone 已关闭或处于睡眠状态(屏幕关闭),您也会收到通知。
我相信你们中的一些人已经实现了类似的东西。
任务准确:
我的应用程序应每天一次通知用户他在日历中安排的活动。
例如:
他选择了 13:00(我一直使用 24 小时格式)来提醒他他的事件。
他在第二天安排了 2 场活动:
- 开车送孩子上学
- 去健身房
第二天在 13:00,应用程序显示一条通知:
"You have two events for today!: 1)... 2)..."
用信息填充通知不是问题。这很好用,我测试了很多。
我只缺少 well-coded background-thread 正在等待 user-chosen 显示通知的时间。
请注意:
TimerTask ticks-intervall 为 1000 毫秒(1 秒)。我确定这不是 well-coded 但它有效。 但我正在寻找更好的 battery-friendly 解决方案。
此外我添加了"android.permission.RECEIVE_BOOT_COMPLETED"和"android.permission.WAKE_LOCK"权限。
该服务被标记为 START_STICKY
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service android:name=".services.NotificationService" android:exported="false"/>
<receiver android:name=".services.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<activity
android:name=".activities.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//Other Activities
</application>
</manifest>
引导接收器:
public class BootReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NotificationService.class));
}
}
通知服务:
public class NotificationService extends Service{
private Calendar currentCalendar, plannedCalendar;
public static final String FILENAME_SETTINGS = "MySettings";
private static final int MODE_PRIVATE = 0;
SharedPreferences data;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private Timer timer;
private TimerTask timerTask = new TimerTask() {
@Override
public void run() {
data = getSharedPreferences(FILENAME_SETTINGS, MODE_PRIVATE);
int plannedHour = data.getInt("alarm_hour", 0);
int plannedMinute = data.getInt("alarm_minute", 0);
plannedCalendar = Calendar.getInstance(Locale.getDefault());
plannedCalendar.set(Calendar.MINUTE, plannedMinute);
plannedCalendar.set(Calendar.HOUR_OF_DAY, plannedHour);
plannedCalendar.set(Calendar.SECOND, 0);
plannedCalendar.set(Calendar.MILLISECOND, 0);
//Kalender aktualisieren
currentCalendar = Calendar.getInstance(Locale.getDefault());
currentCalendar.setTimeInMillis(System.currentTimeMillis());
//Check ob es 00:00:00 Uhr ist --> Notification wieder erwuenscht!!!
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
if(currentCalendar.get(Calendar.SECOND) == 0 && currentCalendar.get(Calendar.MINUTE) == 0 && currentCalendar.get(Calendar.HOUR_OF_DAY) == 0){
SharedPreferences.Editor editor = data.edit();
editor.putBoolean("notification", false);
editor.apply();
}
//Nochmal aktualisieren weil durch den "Check" manipuliert wurde
currentCalendar = Calendar.getInstance(Locale.getDefault());
currentCalendar.setTimeInMillis(System.currentTimeMillis());
if((currentCalendar.getTimeInMillis() >= plannedCalendar.getTimeInMillis()) & !data.getBoolean("notification", false)) {
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
notification();
SharedPreferences.Editor editor = data.edit();
editor.putBoolean("notification", true);
editor.apply();
wakeLock.release();
}
}
};
@Override
public void onCreate(){
super.onCreate();
timer = new Timer();
timer.schedule(timerTask, 0, 1000);
}
@Override
public void onDestroy() {
try{
timer.cancel();
timerTask.cancel();
}catch (Exception e){
e.printStackTrace();
}
Intent intent = new Intent("Intent");
intent.putExtra("VALUE", "blalal");
sendBroadcast(intent);
}
public void notification(){
Context context = getApplicationContext();
Intent intent = new Intent(context, LiveSelectActivity.class);
PendingIntent pen = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(getString(R.string.hineweisTrainingsGeplant))
.setContentText("Content")
.setContentIntent(pen)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_add_white_24dp);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
使用 AlarmManager 安排 Intent
您的服务将在所需时间接收和处理的信息。如果配置正确,它确实可以工作。
我的目标是实现在一天中的 user-chosen 时间出现的通知。
我已经尝试过 Service
,这可行,但问题是它需要大量后台进程(代码在下面),另一个是 AlarmManager
但这似乎无法正常工作,尤其是 API 19+。我在 Whosebug 上找不到 up-to-date well-coded 教程或类似问题的有用答案,所以我求助于您。
你们都知道:如果朋友向您发送 Whatsapp 短信,即使您的 phone 已关闭或处于睡眠状态(屏幕关闭),您也会收到通知。 我相信你们中的一些人已经实现了类似的东西。
任务准确: 我的应用程序应每天一次通知用户他在日历中安排的活动。
例如: 他选择了 13:00(我一直使用 24 小时格式)来提醒他他的事件。 他在第二天安排了 2 场活动: - 开车送孩子上学 - 去健身房
第二天在 13:00,应用程序显示一条通知: "You have two events for today!: 1)... 2)..."
用信息填充通知不是问题。这很好用,我测试了很多。 我只缺少 well-coded background-thread 正在等待 user-chosen 显示通知的时间。
请注意:
TimerTask ticks-intervall 为 1000 毫秒(1 秒)。我确定这不是 well-coded 但它有效。 但我正在寻找更好的 battery-friendly 解决方案。
此外我添加了"android.permission.RECEIVE_BOOT_COMPLETED"和"android.permission.WAKE_LOCK"权限。
该服务被标记为 START_STICKY
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service android:name=".services.NotificationService" android:exported="false"/>
<receiver android:name=".services.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<activity
android:name=".activities.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//Other Activities
</application>
</manifest>
引导接收器:
public class BootReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NotificationService.class));
}
}
通知服务:
public class NotificationService extends Service{
private Calendar currentCalendar, plannedCalendar;
public static final String FILENAME_SETTINGS = "MySettings";
private static final int MODE_PRIVATE = 0;
SharedPreferences data;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private Timer timer;
private TimerTask timerTask = new TimerTask() {
@Override
public void run() {
data = getSharedPreferences(FILENAME_SETTINGS, MODE_PRIVATE);
int plannedHour = data.getInt("alarm_hour", 0);
int plannedMinute = data.getInt("alarm_minute", 0);
plannedCalendar = Calendar.getInstance(Locale.getDefault());
plannedCalendar.set(Calendar.MINUTE, plannedMinute);
plannedCalendar.set(Calendar.HOUR_OF_DAY, plannedHour);
plannedCalendar.set(Calendar.SECOND, 0);
plannedCalendar.set(Calendar.MILLISECOND, 0);
//Kalender aktualisieren
currentCalendar = Calendar.getInstance(Locale.getDefault());
currentCalendar.setTimeInMillis(System.currentTimeMillis());
//Check ob es 00:00:00 Uhr ist --> Notification wieder erwuenscht!!!
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
if(currentCalendar.get(Calendar.SECOND) == 0 && currentCalendar.get(Calendar.MINUTE) == 0 && currentCalendar.get(Calendar.HOUR_OF_DAY) == 0){
SharedPreferences.Editor editor = data.edit();
editor.putBoolean("notification", false);
editor.apply();
}
//Nochmal aktualisieren weil durch den "Check" manipuliert wurde
currentCalendar = Calendar.getInstance(Locale.getDefault());
currentCalendar.setTimeInMillis(System.currentTimeMillis());
if((currentCalendar.getTimeInMillis() >= plannedCalendar.getTimeInMillis()) & !data.getBoolean("notification", false)) {
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
notification();
SharedPreferences.Editor editor = data.edit();
editor.putBoolean("notification", true);
editor.apply();
wakeLock.release();
}
}
};
@Override
public void onCreate(){
super.onCreate();
timer = new Timer();
timer.schedule(timerTask, 0, 1000);
}
@Override
public void onDestroy() {
try{
timer.cancel();
timerTask.cancel();
}catch (Exception e){
e.printStackTrace();
}
Intent intent = new Intent("Intent");
intent.putExtra("VALUE", "blalal");
sendBroadcast(intent);
}
public void notification(){
Context context = getApplicationContext();
Intent intent = new Intent(context, LiveSelectActivity.class);
PendingIntent pen = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(getString(R.string.hineweisTrainingsGeplant))
.setContentText("Content")
.setContentIntent(pen)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_add_white_24dp);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
使用 AlarmManager 安排 Intent
您的服务将在所需时间接收和处理的信息。如果配置正确,它确实可以工作。