2016-01-11 35 views
1

我使用如何使用廣播

String code = intent.getStringExtra("CODE"); 

我得到空指針異常獲取額外的數據時,廣播監聽器類的onReceive方法使用

Intent intent = new Intent(); 
intent.setAction("com.example.android.name"); 
intent.putExtra("CODE", code); 

發送廣播發送數據。 任何幫助如何檢索數據。

public class ReceiveNetworkBroadcast extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     Bundle extras = intent.getExtras(); 
     String code = extras.getString("CODE"); 
     Log.e("NET_BCAST_RECEIVER: ", code); 

    } 

} 

     <receiver 
      android:name=".ReceiveNetworkBroadcast" 
      android:enabled="true" 
      android:exported="true"> 
      <intent-filter> 
       <action android:name="com.example.android.name" /> 
      </intent-filter> 
     </receiver> 

public void sendBroadcast(Context context, String code){ 
     Intent intent = new Intent(); 
     intent.setAction("com.example.android.name"); 
     intent.putExtra("CODE", code); 
     intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 
     context.sendBroadcast(intent); 

    } 
+0

可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how -do-i-fix-it) –

+0

是代碼變量類型的字符串嗎? – nurisezgin

+0

@nurisezgin是的,代碼被定義爲字符串 – Akzwitch

回答

1

努力在bundle這樣Intent演員:

@Override 
public void onReceive(Context context, Intent intent) { 
    // TODO Auto-generated method stub 
    Bundle extras = intent.getExtras(); 
    if (extras != null) { 
     if(extras.containsKey("CODE")){ 
     Object value=extras.get("CODE"); 
     System.out.println(value); 
     } 
    } 

} 

希望這將現在的工作。

+0

第二行仍然是相同的錯誤 – Akzwitch

+0

@Akzwitch試試看,我已經更新了我的答案。 –