2017-08-03 42 views
1

myRange的值始终为1,2或3.创建多个pendingIntent

它给出了一个空指针异常error.pending必须指定。

如果我不检查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; 
} 
+0

你可以发布logcat堆栈跟踪吗? –

回答

0

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

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

这可能会始终返回null为你您指定FLAG_NO_CREATE。如果匹配PendingIntent已经存在(这可能不会),这将只返回非null结果。改为使用FLAG_UPDATE_CURRENT

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

关于此问题,大约有一百万个关于Stackoverflow的问题,并且大多数问题都有关于如何创建和匹配作品的详细说明PendingIntent