这就是您要寻找的:您可以使用警报管理器在特定时间显示通知,即使您的应用程序根本没有运行。
http://developer.android.com/reference/android/app/AlarmManager.html
特定时间的每日通知
这对以下有用:
使用 Alarmmanager 在特定时间启动服务
编辑见评论:
您可以为此使用 AlarmManager,首先为您自己创建某种接收器。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, MyService.class);
context.startService(dailyUpdater);
Log.d("AlarmReceiver", "started service");
}
}
比您需要创建将显示通知的服务
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private NotificationManager mNM;
private int NOTIFICATION = 546;
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return START_STICKY;
}
@Override
public void onDestroy() {
mNM.cancel(NOTIFICATION);
Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
Toast.makeText(this, "show notification", Toast.LENGTH_SHORT).show();
//notification code here
}
}
最后你需要设置闹钟:
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.set(Calendar.HOUR_OF_DAY, 20);
updateTime.set(Calendar.MINUTE, 30);
Intent open = new Intent(context, AlarmReceiver.class);
open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, open, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, 10000, pendingIntent);
}
在您进行测试运行之前,将您的接收器和服务添加到您的清单文件中:
<service android:name=".MyService"></service>
<receiver android:name=".AlarmReceiver"></receiver>