public class MainActivity extends AppCompatActivity{ public static String ACTION_BROADCAST="com.eranewgames.bluetoothdoor.broadcast"; BroadcastReceiver broadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); broadcastReceiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.e("MainActivity=onReceive", intent.getStringExtra("text")); } }; IntentFilter intentFilter=new IntentFilter(MainActivity.ACTION_BROADCAST); registerReceiver(broadcastReceiver,intentFilter); startService(new Intent(MainActivity.this,ServiceBluetoothDoor.class)); } @Override protected void onDestroy() { super.onDestroy(); stopService(new Intent(MainActivity.this,ServiceBluetoothDoor.class)); unregisterReceiver(broadcastReceiver); } } // Service
public class ServiceBluetoothDoor extends Service { String macAddress = "70:72:0D:44:E6:1B"; // SPP UUID сервиса private UUID MY_UUID = UUID.fromString("00001101-0000-6666-8000-00805F23534B"); BluetoothSocket bluetoothSocket; @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { super.onCreate(); BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter(); BluetoothDevice bluetoothDevice=bluetoothAdapter.getRemoteDevice(macAddress); bluetoothAdapter.cancelDiscovery(); try{ bluetoothSocket=bluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID); bluetoothSocket.connect(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(bluetoothSocket.getInputStream())); String line; while ( (line=bufferedReader.readLine()) !=null ){ Log.e("ServiceBluetoothDoor=onCreate", line); // Intent intent=new Intent(MainActivity.ACTION_BROADCAST); // intent.putExtra("text",dataInputStream.readUTF()); // sendBroadcast(intent); } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onDestroy() { super.onDestroy(); try { bluetoothSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } MainActivity hangs, but why is it not connected to the service?