Android: AlarmManager used to call a Service to notify the user

≡放荡痞女 提交于 2019-12-06 08:36:28

Since all you're doing is notifying your user one time, a service is not the best approach for this. Services are meant to do work in the background. A notification is not really the type of work suited for a Service - it's too short. Therefore, I suggest you use a BroadcastReceiver instead.

The class should be something like this:

public class TimerReceiver extends BroadcastReceiver {
  private static final int NOTIFICATION = 3456; 

/*since you're always doing a 1-time notification, we can make this final and static, the number
 won't change. If you want it to change, consider using SharedPreferences or similar to keep track 
 of the number. You would have the same issue with a Service since you call stopself() and so,
 you would delete the object every time.*/

  @Override
  public void onReceive(Context context,Intent intent) {

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.clock_alarm);
    builder.setContentTitle("Time is up");
    builder.setContentText("SLIMS");
    builder.setVibrate(new long[] { 0, 200, 100, 200 });
    final Notification notification = builder.build(); 

    mNM.notify(NOTIFICATION, notification);
  }

To call the receiver, you need to change both the Intent to point to the new class and getService() needs to be getBroadcast(). Therefore this

Intent myIntent = new Intent(getActivity().getApplication(),
                TimersService.class);


PendingIntent pendingIntent = PendingIntent.getService(getActivity()
                .getApplication(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);

needs to be

Intent myIntent = new Intent(getActivity().getApplication(),
                TimerReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity()
                .getApplication(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);

Also, you should be able to safely change getActivity().getApplication() into just getActivity()

Lastly you need a manifest declaration:

<receiver android:name=".TimerReceiver" ></receiver>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!