通知不会起作用

时间:2017-04-05 20:08:19

标签: android notifications android-notifications

我学习编写Android应用程序,我想创建一个简单的应用程序,这将为用户提供每日通知。

我创建了一个应用程序,但只有在我在手机上安装应用程序后几分钟设置通知时间或者我没有将手机与计算机断开连接时,它才有效。

例如 - 昨天22:30我在今天7:30设置闹钟并且它没有工作,然后(7点40分)我将手机连接到电脑,再次安装应用程序,设置警报8,它工作,所以我在21:30设置另一个警报,它没有再次工作。

任何提示或什么?我想我尝试了所有我知道的事情:/

以下是代码:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageButton notificationButton = (ImageButton) findViewById(R.id.nofication_button);

    notificationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            int curHr = calendar.get(Calendar.HOUR_OF_DAY);
            if (curHr > 21)
            {
                // Since current hour is over 21, setting the date to the next day
                calendar.add(Calendar.DATE, 1);
            }
            calendar.set(Calendar.HOUR_OF_DAY, 21);
            calendar.set(Calendar.MINUTE, 30);
            calendar.set(Calendar.SECOND, 12);

            Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    });
}
}

NotificationReceiver类:

public class NotificationReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent1 = new Intent(context, MainActivity.class);
    intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.index)
            .setContentIntent(pendingIntent)
            .setContentText("Notification Text")
            .setContentTitle("Notification Title")
            .setSound(alarmSound)
            .setVibrate(new long[]{1000, 1000, 1000, 1000})
            .setAutoCancel(true);

    notificationManager.notify(0, builder.build());
}
}

0 个答案:

没有答案