Android连接服务场景是指在Android应用程序中使用Service连接到其它组件、外部硬件或应用程序。其中包括:
// 定义ServiceConnection private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { MyService.MyBinder binder = (MyService.MyBinder)iBinder; mService = binder.getService(); }
@Override
public void onServiceDisconnected(ComponentName componentName) {
mService = null;
}
};
// 绑定Service bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
// 定义AIDL接口 interface IMyAidlInterface { int getPid(); }
// 实现AIDL接口 public class MyService extends Service { private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() { @Override public int getPid() throws RemoteException { return Process.myPid(); } };
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
// 客户端绑定AIDL接口 private IMyAidlInterface mService; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { mService = IMyAidlInterface.Stub.asInterface(iBinder); }
@Override
public void onServiceDisconnected(ComponentName componentName) {
mService = null;
}
}; bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
// 获取BluetoothAdapter并打开蓝牙 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
// 扫描可用设备 bluetoothAdapter.startDiscovery();
// 连接设备 private BluetoothDevice mDevice; private BluetoothSocket mSocket; bluetoothAdapter.cancelDiscovery(); mDevice = bluetoothAdapter.getRemoteDevice(deviceAddress);
try { mSocket = mDevice.createRfcommSocketToServiceRecord(MY_UUID); mSocket.connect(); } catch (IOException e) { e.printStackTrace(); }
// 使用HttpURLConnection访问Web服务 private String getUrlContent(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();