我正在创建一个在未来日期显示通知的应用程序。为了在将来显示通知,我已经在 AlarmManager 的帮助下。
在我的一项活动中单击按钮时,我会创建这样的通知
Intent myIntent = new Intent(getApplicationContext(),
BootService.class);
myIntent.putExtra("stuffid", stuffId);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
stuffId, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 00);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pendingIntent);
// Tried set repeating also :(
// alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 30*1000, pendingIntent);
这是我的 BootService 类代码:
public class BootService extends Service {
DBController dbController = new DBController(this);
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LoadAlarmsFromDatabase();
int stuffId = intent.getIntExtra("stuffid", 0);
if(stuffId > 0)
new GetStuffDataAsync().execute(stuffId);
return super.onStartCommand(intent, flags, startId);
}
private void LoadAlarmsFromDatabase() {
DBController dbController = new DBController(this);
// Iterate over array and call addnotification no of time
...
addNotification(stuff.getStuffId(), calendar);
dbController.close();
}
private void addNotification(int stuffid, Calendar cal) {
Calendar rightNow = Calendar.getInstance();
long rightNowMillis = rightNow.getTimeInMillis();
// Add to alarm only when its greate than current date
if (cal.getTimeInMillis() > rightNowMillis) {
Log.v(TAG, "addNotification " + stuffid + ", " + cal);
Intent intent = new Intent(getApplicationContext(),
BootService.class);
intent.putExtra("stuffid", Integer.toString(stuffid));
PendingIntent mAlarmSender = PendingIntent.getBroadcast(
getApplicationContext(), stuffid, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
//am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), mAlarmSender);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, mAlarmSender);
}
}
public class GetStuffDataAsync extends AsyncTask <Integer,Void,Stuff>{
@Override
protected Stuff doInBackground(Integer... params) {
int stuffId = params[0];
Stuff stuff = dbController.getStuffInfo(stuffId);
dbController.close();
return stuff;
}
@Override
protected void onPostExecute(Stuff result) {
Context ctx = getApplicationContext();
Intent notificationIntent = new Intent(ctx, AndroidAlarmService.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
1, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Reminder: " + result.getName() + " expires on " + result.getExpiresOn())
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("NotifyWhenMyStuffExpires")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(result.getName() + " expires on " + result.getExpiresOn());
Resources res = ctx.getResources();
if(result.getHasPhoto() == 1){
Bitmap bm = result.getPhoto();
builder.setContentIntent(contentIntent).setLargeIcon(bm);
}
else
builder.setContentIntent(contentIntent).setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher));
Notification n = builder.build();
nm.notify(1, n);
}
}
}
在测试应用程序时,我看到显示通知,问题是特定于启动手机的。在上面的代码中,我通过调用 LoadAlarmsFromDatabase 重新创建通知
为了在启动时重新创建警报,我使用了 BroadcastReceiver
公共类 BootReceiver 扩展 BroadcastReceiver {
private final String TAG = "BootService";
@Override
public void onReceive(Context context, Intent intent) {
android.os.Debug.waitForDebugger();
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
android.os.Debug.waitForDebugger();
Intent mServiceIntent = new Intent(context,BootService.class);
mServiceIntent.setAction("com.whenmystuffexpires.BootService");
ComponentName service = context.startService(mServiceIntent);
if (null == service) {
// something really wrong here
Log.e(TAG, "Could not start BootService ");
Log.v(TAG, "BootReceiver - Could not start BootService ");
}
} else {
Log.e(TAG, "Received unexpected intent " + intent.toString());
Log.v(TAG, "Received unexpected intent " + intent.toString());
}
}
}
附加调试器后,我看到断点被命中并且 loadalarmfromdatabase 被调用。但是没有显示通知。
这是我的接收者在清单中的声明方式
<service
android:name=".BootService"
android:enabled="true" />
<receiver
android:name=".BootReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
更多事实:
在使用 ADB shell 重新启动时,通知确实有效!
$ 上午广播 -a android.intent.action.BOOT_COMPLETED
我正在姜饼上测试它。
问题仅在手机重启时出现。
清单权限:使用权限 android:name="android.permission.WAKE_LOCK" 使用权限 android:name="android.permission.RECEIVE_BOOT_COMPLETED"