我试图在每天早上8点发出警报。但它根本没有出现。然后我尝试按下按钮,让它在5秒后显示通知。我试过这段代码
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
createNotification(context, "8A.M activity","It's time for breakfast!","Alert");
}
public void createNotification(Context context, String msg, String msgText,String msgAlert){
PendingIntent notificIntent = PendingIntent.getActivity(context,0,new Intent(context, MainActivity.class),0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo_2424)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button nof
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nof = (Button) findViewById(R.id.btnNoftification);
Intent myIntent = new Intent(MainActivity.this , AlarmReceiver.class);
final AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , PendingIntent.getBroadcast(MainActivity.this,1,myIntent,PendingIntent.FLAG_UPDATE_CURRENT)); //set repeating every 24 hours
nof.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Long alertTime = new GregorianCalendar().getTimeInMillis()+5*1000;
Intent alertIntent = new Intent(MainActivity.this,AlarmReceiver.class);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,alertTime,PendingIntent.getBroadcast(MainActivity.this,1,alertIntent,PendingIntent.FLAG_UPDATE_CURRENT));
//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , PendingIntent.getBroadcast(MainActivity.this,1,myIntent,PendingIntent.FLAG_UPDATE_CURRENT)); //set repeating every 24 hours
}
});
我已经在AndroidManifest中添加了权限
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
答案 0 :(得分:0)
将AndroidManifest中的AlarmReceiver类作为<application />
标记内的接收者包含在内。
<receiver android:name=".Alarms.AlarmReceiver"/>