安卓4.1.1的Galaxy Nexus上的安卓接近警报-它真的有效吗



我想使用Android的LocationManager和addProximityAlert方法来设置接近警报。为此,我创建了一个小应用程序,在地图顶部显示十字线,再加上一个用于接近警报名称的文本字段和一个触发添加警报的按钮。

不幸的是,应该接收邻近警报的BroadcastReceiver没有被触发。我已经单独测试了意图(不是通过PendingIntent包装的),这是有效的。此外,我看到一旦设置了接近警报,GPS/位置图标就会出现在通知栏中。

我发现有关接近警报的信息有点令人困惑——有些人告诉我,如果活动不再在前台,就不能使用警报。我认为应该工作,所以我认为其他地方出了问题。

1添加接近报警

GeoPoint geo = mapView.getMapCenter();
Toast.makeText(this, geo.toString(), Toast.LENGTH_LONG).show();
Log.d("demo", "Current center location is: " + geo);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, getLocationAlertIntent(), 0);
locationManager.addProximityAlert(geo.getLatitudeE6()/1E6, geo.getLongitudeE6()/1E6, 1000f, 8*60*60*1000, pIntent);

意图本身就在这里:

private Intent getLocationAlertIntent()
{
Intent intent = new Intent("com.hybris.proxi.LOCATION_ALERT");
intent.putExtra("date", new Date().toString());
intent.putExtra("name", locationName.getEditableText().toString());
return intent;
}

我创建了一个接收器,它应该接收位置警报,在AndroidManifest.xml中注册:

<receiver android:name=".LocationAlertReceiver">
<intent-filter>
<action android:name="com.hybris.proxi.LOCATION_ALERT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

希望实现本身是直接的。它应该显示一个通知(我通过直接发送带有测试按钮的意向来检查)。

public class LocationAlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context ctx, Intent intent) {
Log.d("demo", "Received Intent!");
String dateString = intent.getStringExtra("date");
String locationName = intent.getStringExtra("name");
boolean isEntering = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(ctx)
.setContentTitle("LocAlert: " + locationName)
.setContentText(dateString + "|enter: " + isEntering)
.setSmallIcon(R.drawable.ic_stat_loc_notification)
.build();
notificationManager.notify(randomInteger(), notification);
}
private int randomInteger()
{
Random rand = new Random(System.currentTimeMillis());
return rand.nextInt(1000);
}

有几件事我不能100%确定,也许这会触发你的某些东西:

  • 我认为可以像我一样使用挂起的意图注册接近警报,创建接近警报的"活动"稍后可以关闭
  • 通过getCenter从地图进行转换会返回一个以lat/lon为int值的GeoPoint。我认为我正确地将它们转换为addProximityAlert除以1E6所期望的双值
    • 距离中心的距离相对较大-1000米-我认为这是一个不错的值
    • 我在网上发现的例子使用了以编程方式注册的广播接收器。这不是我想做的。但Reto Meier的《Android 4专业开发》一书提到,在xml中注册广播接收器也是可以的

非常感谢您的帮助!!

我遇到了同样的问题。在我的案例中,明确地设置意图的目标类有帮助。在您的情况下,它应该看起来如下:

private Intent getLocationAlertIntent()
{
Intent intent = new Intent(context, LocationAlertReceiver.class);
intent.setAction("com.hybris.proxi.LOCATION_ALERT"); //not sure if this is needed
intent.putExtra("date", new Date().toString());
intent.putExtra("name", locationName.getEditableText().toString());
return intent;
}

最新更新