为什么AlarmManager没有响应

时间:2015-08-31 17:11:24

标签: android alarmmanager

我对这个问题感到困惑,当我将此代码放在onCreate()方法中(在应用程序启动后5秒钟后启动)它运行良好但是当我将它放在onLocationChangeListener()内时代码不起作用。这是代码:

mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                @Override
                public void onMyLocationChange(Location location) {
                    float[] distance = new float[2];

                    Location.distanceBetween(location.getLatitude(), location.getLongitude(), circle.getCenter().latitude, circle.getCenter().longitude, distance);

                    if (distance[0] > circle.getRadius()) {
                        Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " meters;" + " radius: " + circle.getRadius() + " meters", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " meters;" + " radius: " + circle.getRadius() + " meters", Toast.LENGTH_LONG).show();

                        Intent alertIntent = new Intent(MapsActivity.this, MyService.class);
                        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                        alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, // alertTime is set for 1000 millis. inside onCreate()
                                PendingIntent.getBroadcast(MapsActivity.this, 1, alertIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT));

                    }
                }
            });

我也在网上搜索过,但没有找到与我的问题大致相同的内容。

编辑:这是MyService.java

public class MyService extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    createNotification(context, "AAAAAAAA", "ASDFG", "ASDF");
}

public void createNotification(Context context, String msg, String msgText, String msgAlert) {


    PendingIntent notificIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, MapsActivity.class), 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.searchicon)
                    .setContentTitle(msg)
                    .setTicker(msgAlert)
                    .setContentText(msgText);

    mBuilder.setContentIntent(notificIntent);
    mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    mBuilder.setAutoCancel(true);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());

}}

1 个答案:

答案 0 :(得分:0)

您的闹钟已设置过去。您是否计划过导致警报触发的事件序列?以下是目前发生的情况:

  1. 已创建活动
  2. 将来警报时间设置为1秒(从创建时间活动开始)。
  3. 仅在位置更改时设置警报。
  4. 位置在未来一段时间内会发生变化,可能超过1秒钟。
  5. 警报现在已设置为过去一段时间。