0
votes

How can I start application in my android phone when some bluetooth device is connected?

I'm trying to do this with broadcast receiver, but I have one problem... when I finish activity (exit application), the broadcast receiver must be unregistered... so there is no way to listen to connected devices...

How to keep this broadcast receiver alive, after application is finished?

Thanks

EDIT:

public class AutostartReceiver extends BroadcastReceiver
{
    /**
     * @param context Context
     * @param intent Intent
     * @return void
     */
    @Override
    public void onReceive(Context context, Intent intent)
    {

        String action = intent.getAction();

        switch (action)
        {
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                Log.v("PAREK", "cnn");
                break;

            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                Log.v("PAREK", "dnn");
                break;
        }
    }
}

I also tryied with just manifest initialization

<receiver
            android:name=".Model.Tools.AutostartReceiver">
            <intent-filter>
                <action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED" />
                <action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED" />
                <action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED" />
            </intent-filter>
        </receiver>

EDIT2:

Why? Because I want my app will work only in the car... so when the application is connected to car's hands-free, application will start... and after 5 minutes of disconnection, app will be "terminated".

1

1 Answers

0
votes

You're going to want to register the broadcast receiver in a Service instead of your activity, and return START_STICKY in the onStartCommand to keep it running even after the activity is killed. Example:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}