简体   繁体   中英

Create Android Alarm notification

How do I make my notification as an alarm, at the moment I only get the notification when I am inside the app.

MainActivity:

public void sendNotificationIfTimeEnd01() {
    Context context = getApplicationContext();
    Intent intent01 = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent01 = PendingIntent.getActivity(this, 1, intent01, 0);
    NotificationCompat.Builder builder01 = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notification)
            .setContentIntent(pendingIntent01)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setContentTitle(gamesJuliToStringArray[0])
            .setContentText("ready")
            .setSubText("clkick");
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID_01, builder01.build());
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Maybe you should use Service as running in background while you get out of the app. As i read your description, seems like you put it in an activity. When you go back to home, the app is on pause state. I recommend you run a background service.

try check: Service

I just try to edit the tutorial from Google

public class HelloIntentService extends IntentService {

  /**
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }


  @Override
  protected void onHandleIntent(Intent intent) {
      //maybe some works you need to do
      //sleep for the time until you want the notification
      //put you notification code here
  }
}

This method only in case you have works to do until the job finish and send the notification to alarm user.

But if you are doing an alarm clock that use notification. Maybe you can also try to use some thing like AlarmManager, Receiver to implement. And I find an example this webpage: http://javapapers.com/android/android-alarm-clock-tutorial/

Sorry for my bad English and hope this may help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM