Question

I am developing an application that is using bluetooth to automatically connect to nearby paired devices. For that reason I need to listen to bluetooth specific broadcasts like ACTION_FOUND, DISCOVERY_FINISHED etc. , I have to register a broadcast receiver which listens for those broadcasts and performs actions accordingly. Thing is that I need this broadcast receiver to work at any time in the background of my app. I tried to fit it into an intentservice but it turned out that it finishes to fast and onDestroy is called ending my receiver. To overcome this problem I inserted an infinite loop which breaks only when an attribute is turned from true to false. Somehow I feel this is a bad practice and so I am asking you if there is any better solution?

PS. Should I fit the receiver in the main activity? And when does it gets destroyed? Is onDestroy called only when I exit my application with back button, or kill the process with a task killer, or does it occur also when I enter another GUI window in my app?

Thanks, Mike

Was it helpful?

Solution

If you register your receiver dynamically (Context.registerReceiver) it is your job to unregister it (Context.unregisterReceiver) before your activity is paused. And as reading from the documentation:

You won't receive intents when paused, and this will cut down on unnecessary system overhead

onPause will be called when something hides your activity. And you can re register in onResume.

However, this is not what you need. If you want to receive broadcasts even while your application is dead, you need to declare it in the Android Manifest. I think this code will work:

    <receiver android:name=".YourReceiverClassName">
        <intent-filter>
            <action android:name="android.bluetooth.adapter.action.ACTION_FOUND"/>
            <action android:name="android.bluetooth.adapter.action.ACTION_DISCOVERY_FINISHED"/>
        </intent-filter>
    </receiver>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top