gpt4 book ai didi

android - IntentReceiver 不起作用

转载 作者:行者123 更新时间:2023-11-29 02:12:13 27 4
gpt4 key购买 nike

我使用 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 位置时没有任何反应。怎么了?我试过在 list 中注册 Receiver,但没有用。

附言当我使用 getActivity 而不是 getBroadcast 时,它工作正常并恢复了我的 Activity(如果它已经死了)。

最佳答案

好的,伙计们。无论如何。现在我明白了 Intents 是如何工作的。最主要的是(我想是)我使用了不同的上下文。

现在我有了自己的类,其中包含使用 PendingIntent 调用的 addProximityAlert 函数。我传递了 WrapperContext activityContext 而不是 this(当我创建我的类时,我传递了我的 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 可能在您捕捉到它之前就已经死了。

第二件事 - 我在 list 中使用 action="@strings/my_message"注册了 intent-filter:

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

我希望这对某人有用。

关于android - IntentReceiver 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6612716/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com