0

我意识到这个问题已经存在,但我在实施解决方案时遇到了麻烦。

我使用这些问题作为指导方针:

基于服务的多重邻近警报

使用相同的广播设置 2 个接近警报

我在哪里注册接收器:

final String NEAR_YOU_INTENT = "neighborhood.crodgers.example.activities.PROXIMITY_ALERT";
IntentFilter filter = new IntentFilter(NEAR_YOU_INTENT);
registerReceiver(new LocationReceiver(), filter);

添加接近警报的位置(注意:这是在服务中完成的,因此是上下文抓取):

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
final String NEAR_YOU_INTENT = "neighborhood.crodgers.example.activities.PROXIMITY_ALERT";
Context context = getApplication().getApplicationContext();

int requestCode = 12345; //Spaceballs, anyone? anyone?
for (String domain : domainNames)
{
    String[] itemNames = itemGetter();
    for (String item : itemNames)
    {
        HashMap<String, String> attributes = getAttributesForItem(domain, item);                    

        Intent intent = new Intent(NEAR_YOU_INTENT);
        intent.putExtra(ADDRESS, attributes.get(ADDRESS));
        intent.setAction(""+requestCode);
        PendingIntent proximity = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        manager.addProximityAlert(Double.parseDouble(attributes.get(LATITUDE)),
                                  Double.parseDouble(attributes.get(LONGITUDE)), 
                                  6000f, -1, proximity);

        requestCode++;
    }
}

最初,我收到了添加第一个接近警报的通知(使用来自接收器的通知)。添加后

intent.setAction(""+requestCode);

我也试过:

intent.setData(""+ requestCode)

(我在其他几个地方看到过这个推荐)我不再一起收到通知了。

4

1 回答 1

3

问题

问题是您使用 setAction

Intent intent = new Intent(NEAR_YOU_INTENT);
intent.putExtra(ADDRESS, attributes.get(ADDRESS));
intent.setAction(""+requestCode); //HERE IS THE PROBLEM

您最终在最后一行中所做的是将操作从 NEAR_YOUR_INTENT 更改为任何请求代码。IE,你正在做相当于

    Intent intent = new Intent();
    intent.setAction(NEAR_YOUR_INTENT);
    intent.setAction(""+requestCode); // THIS OVERWRITES OLD ACTION

额外的方法

我怀疑您真正想要做的是将 requestCode 添加为意图的额外内容,以便您可以在接收器中检索它。尝试使用

    Intent intent = new Intent(NEAR_YOU_INTENT);
    intent.putExtra(ADDRESS, attributes.get(ADDRESS));
    intent.putExtra("RequestCode", requestCode);

数据方法

或者,您可以将数据设置为您的请求代码。IE,你可以使用

    Intent intent = new Intent(NEAR_YOU_INTENT);
    intent.putExtra(ADDRESS, attributes.get(ADDRESS));
    intent.setData("code://" + requestCode);

然后您需要更改您的接收器,以便它可以接受“code://”模式。去做这个:

final String NEAR_YOU_INTENT = "neighborhood.crodgers.example.activities.PROXIMITY_ALERT";
IntentFilter filter = new IntentFilter(NEAR_YOU_INTENT);
filter.addDataScheme("code");
registerReceiver(new LocationReceiver(), filter);

然后,当您获得意图时,您可能可以使用某种方法从数据字段中解析出 id。IMO,额外的方法更容易。

于 2011-12-15T18:12:04.133 回答