2016-07-15 115 views
1

我有一個科爾多瓦插件,掃描條形碼,使用一個名爲「com.hyipc.core.service.barcode.BarcodeService2D」服務。這是通過向廣播接收器註冊接收器完成的。使用callbackContext內廣播接收器

掃描過程運行成功,但我想送回到我的科爾多瓦的應用程序掃描結果,我所看見的使用callbackContext.success(strBarcode)完成。問題是我不能在BarcodeReceiverClass中使用它。有什麼方法可以將onReceive中的數據發送回我的應用程序?

public class Scanner extends CordovaPlugin { 

    private BroadcastReceiver mReceiver = new BarcodeReceiver(); 
    private Intent intentService = new Intent("com.hyipc.core.service.barcode.BarcodeService2D"); 
    public static final String ACTION_BARCODE_SERVICE_BROADCAST = "action_barcode_broadcast"; 
    public static final String KEY_BARCODE_STR = "key_barcode_string"; 
    private String strBarcode = ""; 

    @Override 
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { 

     if (action.equals("scan")) { 
      scan(); 
      return true; 
     } else { 
      return false; 
    } 
} 

    public void scan() { 
     IntentFilter filter = new IntentFilter(); 
     filter.addAction(ACTION_BARCODE_SERVICE_BROADCAST); 

     cordova.getActivity().startService(intentService); 
     cordova.getActivity().registerReceiver(mReceiver, filter); 
    } 

    public class BarcodeReceiver extends BroadcastReceiver { 
     public void onReceive(Context ctx, Intent intent) { 
      if (intent.getAction().equals(ACTION_BARCODE_SERVICE_BROADCAST)) { 
       strBarcode = intent.getExtras().getString(KEY_BARCODE_STR); 
       callbackContext.success(strBarcode); 
      } 
     } 
    } 
} 

回答

3

您需要回調上下文參數傳遞給你BarcodeReceiver類:

public class Scanner extends CordovaPlugin { 
    .... 
    private BroadcastReceiver mReceiver = null; 

    @Override 
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { 
     .... 
     mReceiver = new BarcodeReceiver(callbackContext); 
     .... 
    } 
    .... 
} 

public class BarcodeReceiver extends BroadcastReceiver { 

    private CallbackContext callbackContext; 

    public BarcodeReceiver (CallbackContext callbackContext) { 
     this.callbackContext = callbackContext; 
    } 

    public void onReceive(Context ctx, Intent intent) { 
     if (intent.getAction().equals(ACTION_BARCODE_SERVICE_BROADCAST)) { 
      strBarcode = intent.getExtras().getString(KEY_BARCODE_STR); 
      callbackContext.success(strBarcode); 
     } 
    } 
} 
+0

我得到一個生成錯誤:表達式的非法啓動 私人廣播接收器mReceiver =新BarcodeReceiver(callbackContext); –

+0

對不起,請查看我的代碼編輯,範圍是發送參數callbackContext到BarcodeReceiver類。爲了做到這一點,你需要在BarcodeReceiver的構造函數中添加它,然後在從CordovaPlugin子類中實例化這個類時傳遞它。 – Frix33

+0

是的,現在它可以工作,謝謝。我將獎勵21小時(StackOverflow上它不會讓我做,直到比) –