在我的Android应用程序上运行Emulator时,我遇到了一些问题,无法让我的接近警报工作。基本上,接近警报应该启动一个活动,该活动将(暂时)打印到日志中,但是,当为警报设置了所需的位置,并且仿真器的位置设置在该特定位置时,什么也不会发生。以下是接近警报的代码:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent(MY_PROXIMITY_ALERT);
PendingIntent proxIntent = PendingIntent.getActivity(MapActivity.this, 0, intent, 0);
lm.addProximityAlert(latlng.latitude, latlng.longitude, 100, -1, proxIntent);现在在清单中声明了MY_PROXIMITY_ALERT,如下所述:
<receiver android:name=".myLocationReceiver">
<intent-filter>
<action android:name="PROXIMITY_ALERT"/>
</intent-filter>
</receiver>下面是我的myLocationReceiver代码
public class myLocationReceiver extends BroadcastReceiver{
private static final String TAG = "myLocationReceiver";
@Override
public void onReceive(Context context, Intent intent) {
final String key = LocationManager.KEY_PROXIMITY_ENTERING;
final Boolean entering = intent.getBooleanExtra(key, false);
if(entering) {
Log.d(TAG, "onReceive: Entering proximity of location");
}
}}
我相信我的问题与Intent或PendingIntent对象有关,但我不能完全确定。我还听说GPS通常需要大约一分钟的时间才能真正注册到附近,但即使过了一段时间,我仍然没有收到日志消息。
谢谢!
发布于 2018-04-25 21:20:38
您已经使用操作MY_PROXIMITY_ALERT创建了一个Intent,然后使用PendingIntent.getActivity()获取了一个要传递给LocationManager的PendingIntent。当满足接近条件时,LocationManager将尝试启动正在侦听操作MY_PROXIMITY_ALERT的Activity。
Intent intent = new Intent(MY_PROXIMITY_ALERT);
PendingIntent proxIntent = PendingIntent.getActivity(MapActivity.this, 0, intent, 0);在清单中,您已经声明了一个侦听操作MY_PROXIMITY_ALERT的BroadcastReceiver。这行不通的。
由于您希望邻近警报触发BroadcastReceiver,因此需要像这样获取PendingIntent:
Intent intent = new Intent(MY_PROXIMITY_ALERT);
PendingIntent proxIntent = PendingIntent.getBroadcast(MapActivity.this, 0, intent, 0);就我个人而言,我认为使用“显式”Intent而不是“隐式”Intent会更好。在这种情况下,您可以这样做:
Intent intent = new Intent(MapActivity.this, myLocationReceiver.class);
PendingIntent proxIntent = PendingIntent.getBroadcast(MapActivity.this, 0, intent, 0);您不需要在Intent中使用该操作。
使用一个“显式的”Intent告诉Android确切地启动哪个组件(类)。如果你使用“隐式”Intent,安卓必须搜索那些宣称它们可以处理某些操作的组件。
https://stackoverflow.com/questions/50013340
复制相似问题