我尝试在特定时间设置通知,并在每24小时后重复一次。运行代码时,服务不会启动或重复。我可以做错了吗?
这是警报管理器的代码
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, myService.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// Set the alarm to start at 8:30 a.p.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 30);
// setRepeating() lets you specify a precise custom interval--in this case,
// after 24 hours minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60*24, alarmIntent);
这是包含通知代码的服务的类
public class myService extends Service {
private NotificationManager nManager;
private static int HELLO_ID;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
String ns = this.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Hello"; // ticker-text
long when = System.currentTimeMillis();
Context context = getApplicationContext();
CharSequence contentTitle = "Hello";
CharSequence contentText = "Hello";
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
// and this
HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
通知无法启动且无法重复。请帮帮我
答案 0 :(得分:0)
Alarm Manager文档说:
此类提供对系统警报服务的访问。这些允许 你安排你的应用程序在运行中的某个时刻运行 未来。当闹钟响起时,已注册的意图 因为它是由系统广播的
意图需要注册警报。当警报响起时,系统将广播意图,并且将执行广播接收器的onReceive()方法内的代码。如果你想执行一些长时间的任务,那么使用服务来做到这一点。以下是在应用程序中设置警报功能的快速步骤:
步骤1:创建广播接收器
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//start service. It is better to use service to perform long time task
}
}
步骤2:设置闹钟
Intent alarmIntent = new Intent(MyActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 0, alarmIntent, 0);
AlarmManager alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
alarmMgr .setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);