在我的UiFragment
frgament中,我尝试连接设备。
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data);
}
break;
}
}
我还有StartScanService
课程,我需要做类似于setResult
的课程(就像我在Activity课程中那样)
public class StartScanService extends Service {
...
...
private void connect(String tmp){
adapter.cancelDiscovery();
String address = tmp.substring(tmp.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result
//setResult(Activity.RESULT_OK, intent);
}
}
所以我需要从服务类调用片段类方法。有可能吗?
答案 0 :(得分:0)
我是使用界面做的。首先我创建界面
public interface ServiceCallBack {
void connectToDevice(Intent intent);
}
在我的服务类中,我调用了接口方法' connectToDevice'
public class StartScanService extends Service {
...
...
...
private ServiceCallBack serviceCallBack;
private void connect(String tmp){
adapter.cancelDiscovery();
String address = tmp.substring(tmp.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
if (serviceCallBack != null) {
serviceCallBack.connectToDevice(intent);
}
}
}
My Fragment类必须实现ServiceCallBack接口
public class UiFragment extends Fragment implements ServiceCallBack{
private ServiceConnection connectionService = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG + " VEG", "onServiceConnected");
StartScanService.ScanBinder scan = (StartScanService.ScanBinder) service;
startScanService = scan.getScanService();
startScanService.setHandler(handler);
startScanService.setServiceCallBack(UiFragment.this);
startScanService.startScan();
bound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
bound = false;
Log.d(TAG, "onServiceDisconnected");
}
};
@Override
public void connectToDevice(Intent intent) {
connectDevice(intent);
}
}