使用setresult()将数据传递给activity

时间:2017-03-07 03:06:21

标签: android

我正在Android Studio中开发一个程序来连接到特定的BLE设备。一旦发现BLE设备,我就使用setresult()返回BLE设备名称等。不幸的是,setresult()给出了一个错误:

  

错误:(201,25)错误:类BroadcastReceiver中的方法setResult不能应用于给定类型;
  required:int,String,Bundle,found:int,Intent,reason:actual和formal参数列表的长度不同

为什么会出现错误,如何解决?

 private final BroadcastReceiver bleServiceReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent sintent) {
        final String action = sintent.getAction();
        if (MldpBluetoothService.ACTION_BLE_SCAN_RESULT.equals(action)) {                       //Service has sent a scan result
            Log.d(TAG, "Scan scan result received");
            final BleDevice device = new BleDevice(sintent.getStringExtra(MldpBluetoothService.INTENT_EXTRA_SERVICE_ADDRESS), sintent.getStringExtra(MldpBluetoothService.INTENT_EXTRA_SERVICE_NAME)); //Create new item to hold name and address

            if(device.getName() != null) {

                if (device.getName().contains("Prodigy")) {                                         //+++++ Added by Chris
                    bleDeviceListAdapter.addDevice(device);                                         //+++++ if Prodigy add to the device to list adapter that displays a list on the screen
                    bleDeviceListAdapter.notifyDataSetChanged();                                    //+++++ Refresh the list on the screen
                    scanStopHandler.removeCallbacks(stopScan);                                                  //Stop the scan timeout handler from calling the runnable to stop the scan
                    scanStop();
                    final Intent intent = new Intent();                                                         //Create Intent to return information to the MldpTerminalActivity that started this activity
                    intent.putExtra(INTENT_EXTRA_SCAN_AUTO_CONNECT, alwaysConnectCheckBox.isChecked());          //Add to the Intent whether to automatically connect next time
                    intent.putExtra(INTENT_EXTRA_SCAN_NAME, device.getName());                                  //Add BLE device name to the intent
                    intent.putExtra(INTENT_EXTRA_SCAN_ADDRESS, device.getAddress());                             //Add BLE device address to the intent
                    setResult(Activity.RESULT_OK, intent);                                                  //Return an intent to the calling activity with the selected BLE name and address
                    finish();
                }
            }

        }
    }
};

1 个答案:

答案 0 :(得分:1)

当您的代码放在broadcastReceiver中时,您正在使用setResult()进行BroadcastReceiver。 如果您的活动中有此broadcastReceiver,请尝试

YourActivity.this.setResult();

如果它不在您的活动范围内,您可能需要在broadcastReceiver中保留活动参考以进行调用

yourActivityReference.setResult();