2017-08-03 92 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