我使用addProximityAlert:
Intent intent = new Intent(getString(R.string.intent_message_location_fetched));
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
locationManager.addProximityAlert(LAT, LONG, RADIUS, 0, proximityIntent);
正如我理解动作的意图,R.string.intent_message_location_fetched应该在位置将在LAT LONG附近被触发。 (R.string.intent_message_location_fetched = com.myapp.client.MyActivity.LocationFetched)
然后我正在尝试创建BroadcastReceiver类:
public class MyBroadcastReciver extends BroadcastReceiver {
MyActivity mainActivity;
public MyBroadcastReciver(MyActivity activity)
{
mainActivity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
mainActivity.ShowToast("Recived : " + intent.getAction());
}
}
在MyActivity类中注册接收器:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
myReciver = new MyBroadcastReciver(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(getString(R.string.intent_message_location_fetched));
registerReceiver(myReciver, intentFilter);
...
但是当我在LAT LONG位置时没有任何反应。 怎么了? 我已经尝试在清单中注册Receiver,但它没有帮助。
P.S。当我使用getActivity而不是getBroadcast时,这可以正常工作并恢复我的Activity,如果它已经死了。
答案 0 :(得分:1)
现在我有自己的类,使用PendingIntent调用addProximityAlert函数。而不是这个我传递了 WrapperContext activityContext (当我创建我的类时,我传递了我的Activity的示例):
//Prepare proximity Intent
proximityIntent = new Intent(activityContext.getString(R.string.intent_message_location_fetched));
proximityPendingIntent = PendingIntent.getBroadcast(activityContext, 0, proximityIntent, 0);
locationManager.addProximityAlert(latitude, longitude, (float) radius, -1, proximityPendingIntent);
注意到期值= -1!或者你的意图可能会在你抓住它之前就已经死了。
第二件事 - 我在清单中注册了intent-filter with action =“@ strings / my_message”:
<activity ...>
...
<intent-filter>
<action android:name="@string/intent_message_location_fetched"/>
</intent-filter>
</activity>
然后我在我自己的类构造函数中有这个:
//Create and register receiver
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(context.getString(R.string.intent_message_location_fetched))
&& intent.getExtras().getBoolean(LocationManager.KEY_PROXIMITY_ENTERING))
{
Toast.makeText(activityContext, "LOCATION INTENT WORKS!", Toast.LENGTH_SHORT).show();
}
}
};
activityContext.registerReceiver(mReceiver, new IntentFilter(activityContext.getString(R.string.intent_message_location_fetched)));
我希望这对某人有用。