Android: Shut down / loss of bluetooth connection or file receive -> Do something

大城市里の小女人 提交于 2019-12-10 10:00:59

问题


I want to write an App that monitors my paired bluetooth connection in the following way:

If a file comes from a paired source it should be stored. If no file was passed and the bluetooth connection breaks down, my app shall store a dummy file.

Storing a file works great, my main issue is how to run this whole thing without having an activity on my display....

I read much about services, but mostly it is said that a service is depending on an activity/app...is that right?

Is there any other possibility to realize something like that? What about broadcast receivers? How can I programm this functionality?

I'm looking forward to read your (creative) answers ;-) nice greetings, poeschlorn


回答1:


As you guessed, you could do this with a BroadcastReceiver and a Service. You would setup your broadcast receiver to handle the "bluetooth disconnect" event, and then fire off the service to do something about it.

In the manifest, declare your receiver:

<receiver android:name=".YourReceiver">
    <intent-filter>
        <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/>
    </intent-filter>
</receiver>

In your BroadcastReceiver, you would do something like this:

@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
        context.startService(new Intent(context, YourService.class));
    }
}

And your Service would handle creating the dummy file:

@Override
public void onCreate() {
    // Create the dummy file, etc...
}

You'll also want to do things like check the device that's being disconnected, etc, but this should get you started. Also, I've never used the Bluetooth stack, but I think that's the relevant action name.



来源:https://stackoverflow.com/questions/2905240/android-shut-down-loss-of-bluetooth-connection-or-file-receive-do-somethin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!