package com.javispedro.autobluetether; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import java.util.Set; public class BtConnectReceiver extends BroadcastReceiver { private static final String TAG = "BtConnectReceiver"; private boolean isDeviceEnabled(Context context, BluetoothDevice device) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Set enabledAddresses = prefs.getStringSet(context.getString(R.string.prefs_key_device_list), null); if (enabledAddresses == null) return false; Log.d(TAG, "enabled devices in prefs: " + enabledAddresses); return enabledAddresses.contains(device.getAddress()); } @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action == null) return; if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device == null) return; Log.d(TAG, "ACL connected: " + device.getName()); if (isDeviceEnabled(context, device)) { Log.d(TAG, "trying to enable tethering"); try { new BtTetherEnabler(context).startTethering(); } catch (BtTetherEnabler.EnableException e) { e.printStackTrace(); Log.e(TAG, "Can't enable tethering: " + e.getMessage()); } } } } }