创建多个pendingIntent

时间:2017-08-03 20:50:35

标签: android android-pendingintent

myRange的值始终为1,2或3。

它给出了一个nullpointer异常错误。必须指定。

如果我没有在if语句中检查myRange值,它不会给出错误,但它不会创建pendingIntent2和pendingIntent3。

我尝试发送不同的请求代码,但它不起作用。

  private PendingIntent createGeofencePendingIntent(int myRange) {
    Log.d(TAG, "createGeofencePendingIntent");
    Toast.makeText(getContext(),"creating intent function" + myRange ,Toast.LENGTH_SHORT).show();

    if ( geoFencePendingIntent1 != null && myRange == 1)
        return geoFencePendingIntent1;
    if ( geoFencePendingIntent2 != null  && myRange == 2 )
        return geoFencePendingIntent2;
    if ( geoFencePendingIntent3 != null  && myRange == 3)
        return geoFencePendingIntent3;

    if(myRange == 1)
      {
         Toast.makeText(getContext(),"creating intent 1",Toast.LENGTH_SHORT).show();
          Intent intent1 = new Intent( getContext(), GeofenceTransitionService.class);
          intent1.putExtra("region",inString[0]);
           geoFencePendingIntent1 = PendingIntent.getService(
                  getContext(), GEOFENCE_REQ_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT );
            return geoFencePendingIntent1;
      }
    else if (myRange ==2)
        {
            Toast.makeText(getContext(),"creating intent 2",Toast.LENGTH_SHORT).show();
            Intent intent2 = new Intent( getContext(), GeofenceTransitionService.class);
            intent2.putExtra("region",inString[1]);
            geoFencePendingIntent2 =  PendingIntent.getService(
                    getContext(), 5, intent2, PendingIntent.FLAG_NO_CREATE );
            return geoFencePendingIntent2;
        }
    else if (myRange == 3)
        {
            Intent intent3 = new Intent( getContext(), GeofenceTransitionService.class);
            return PendingIntent.getService(
                    getContext(), GEOFENCE_REQ_CODE, intent3, PendingIntent.FLAG_UPDATE_CURRENT );

        }




    geoRange++;
   // Toast.makeText(getContext(), "leaving my geofence", Toast.LENGTH_SHORT).show();
    return null;
}

1 个答案:

答案 0 :(得分:0)

这里有几个问题。第一个是:

       geoFencePendingIntent2 =  PendingIntent.getService(
                getContext(), 5, intent2, PendingIntent.FLAG_NO_CREATE );

这可能始终返回null,因为您已指定FLAG_NO_CREATE。如果匹配的null已经存在(它可能不存在),则只返回非PendingIntent结果。请改用FLAG_UPDATE_CURRENT

第二个问题是你需要确保3个不同的PendingIntent中的每一个都是唯一的。为此,您需要在requestCode的调用中提供唯一的PendingIntent.getService(),或者您需要在传递给Intent的{​​{1}}中提供唯一的操作。否则,当您致电PendingIntent.getService()时,您将继续获得相同的PendingIntent.getService()返回(并且不会创建新的PendingIntent

Stackoverflow上有大约一百万个关于此的问题,其中大多数问题都详细解释了PendingIntent创建和匹配的工作原理。