Android:AlarmManager用于调用服务以通知用户 [英] Android: AlarmManager used to call a Service to notify the user

查看:81
本文介绍了Android:AlarmManager用于调用服务以通知用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑在清单中添加此行解决了我的问题(Service创建得很好).

Edit Adding this line in my manifest solved my problem (the Service is well created).

<service android:name=".TimersService" >

发布

我当前正在尝试实施警报,以通知用户倒计时已经结束.我有一个方法createAlarm(),它通过AlarmManager添加了一个新的Alarm.当前在Fragment内部调用此方法.看起来像这样:

I'm currently trying to implement alarms to notify the user that a countdown has finished. I have a method createAlarm() that adds a new Alarm through an AlarmManager. This method is currently called inside a Fragment. It looks like this:

private final void createAlarm(String name, long milliInFuture) {

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

        AlarmManager alarmManager = (AlarmManager) getActivity()
                .getSystemService(Context.ALARM_SERVICE);

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

        alarmManager.set(AlarmManager.RTC_WAKEUP,
                milliInFuture, pendingIntent); 

    }

我希望此方法可以添加警报.即使设备处于睡眠模式,也应调用该警报.它应该在时间milliInFuture(有时是System.currentTimeMillis() +)被调用.警报启动时,它应该启动服务.该服务如下.此Service应该只做一件事:通知用户警报已完成.我的Service类如下:

I expect this method to add an Alarm. The Alarm should be called even if the device is in sleep mode. It should be called at time milliInFuture (which is System.currentTimeMillis()+ some time). When the alarm is up, it should start a Service. The Service is the following. This Service should do only one thing: notify the user that the alarm has finished. My Service class is as follows:

public class TimersService extends Service {

    private NotificationManager mNM;
    private int NOTIFICATION = 3456;


    public class LocalBinder extends Binder {
        TimersService getService() {
            return TimersService.this;
        }
    }

    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
            return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mNM.cancel(NOTIFICATION);
        Toast.makeText(this, "Alarm", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

        private final IBinder mBinder = new LocalBinder();

    private void showNotification() {

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
        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);
        NOTIFICATION += 1;
    }

}

运行代码时,将调用我的方法createAlarm.但是我的服务从未创建.我是根据此处找到的亚历山大的Fragotsis的代码编写的.我的Service类的灵感来自

When I run my code, my method createAlarm is called. But my Service is never created. I wrote this code based on Alexander's Fragotsis's one found here. And my Service class is inspired from the Android references of the Service class.

有人知道为什么我的Service没有被调用吗? Manifest关于警报,服务或通知,我应该写些什么吗?

Any idea why my Service is not being called ? Is there anything I should write in my Manifest about the Alarm,Service or Notification ?

谢谢您的帮助

Ho,对于我的代码提出的任何建议,我将不胜感激.如果您知道在固定的时间后更轻松地通知用户的方法,请告诉我!

Ho and I would appreciate any suggestion about my code. If you know an easier way to notify the user after a fixed amount of time, let me know !

推荐答案

由于您所做的只是一次通知您的用户,因此服务并不是最好的方法.服务旨在在后台工作.通知实际上不是适合服务的工作类型-太短了.因此,建议您改用BroadcastReceiver.

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.

该类应该是这样的:

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);
  }

要调用接收方,您需要同时更改指向新类的Intent和getService()必须为getBroadcast().因此,

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);

需要成为

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

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

此外,您应该可以安全地将getActivity().getApplication()更改为getActivity()

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

最后,您需要一个清单声明:

Lastly you need a manifest declaration:

<receiver android:name=".TimerReceiver" ></receiver>

这篇关于Android:AlarmManager用于调用服务以通知用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆