Creating Service with Bluetooth activation in Android

穿精又带淫゛_ 提交于 2019-12-12 03:52:59

问题


I want to create a service in Android which will initially ask user if they want to start Bluetooth and set the Bluetooth discovery.

My question is:

  1. Can I launch in the service following activities?

    if (!mBluetoothAdapter.isEnabled())
    {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 0);
    }
    
    // Set Phone Discoverable for 300 seconds.
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600);
    startActivity(discoverableIntent);
    
  2. I want to set discoverabilty of the phone on for lifetime of application. Is it possible?

  3. I want to access empty space available on SD card. How should i do it?

Thanks in advance.


回答1:


1) You cannot use that particular code because you cannot call startActivity() from a service. You would need to use the following code to enable the Bluetooth:

BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapter.enable();

The documentation says

boolean enable()

Turn on the local Bluetooth adapter—do not use without explicit user action to turn on Bluetooth.

So you need to be sure to prompt the user first. Also you cannot set the device to be discoverable in the service because the only way to do that is with the startActivity() so you would need to do that part in some kind of a configuration Activity.

2) No, having a Bluetooth device be discoverable opens it up to a multitude of security concerns, so not only is it not possible, it's a bad idea.

3) If you want to write to the SDCard you just need to add the WRITE_EXTERNAL_STORAGE permission to your manifest file and then you can use standard Java File IO.



来源:https://stackoverflow.com/questions/2585332/creating-service-with-bluetooth-activation-in-android

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