我在stackoverflow上读了近30个线程,我不能让这个代码工作..我需要每天下午14点通知。我在Logcat中没有得到任何错误“waitforAlarm result:some integer”。我很绝望......
Heres是我的代码:
清单:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
Notifications.class
public class Notifications extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0 , notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification(R.drawable.icona, "huhu", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, "asdas", "huhu", contentIntent);
mNotificationManager.notify(0, notification);
}
}
Main.class
public void AlarmMethod(){
Intent myIntent = new Intent(this, Notifications.class);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 14);
//calendar.set(Calendar.AM_PM, Calendar.AM);
//calendar.add(Calendar.DAY_OF_MONTH, 1);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent);
}
问题已解决:
最后我离开这个方法,我使用广播接收器:
答案 0 :(得分:0)
@Override
public void onCreate(){
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, Main.class);
notificationIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0,
notificationIntent, 0);
Notification noti = new Notification.Builder(getApplicationContext())
.setContentTitle("PACS Notification")
.setContentText(Alarm Notification from Alarm Manager")
.setSmallIcon(R.drawable.icona)
.setContentIntent(pIntent ).build();
noti.flags |= Notification.FLAG_AUTO_CANCEL;
noti.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
mNotificationManager .notify(0, noti);
}
注意:强> Plz在androidmanifest.xml上添加你的服务类as,
<service android:enabled="true" android:name=".Notifications " />