具有BluetoothAdapter.ACTION_STATE_CHANGED动作的广播接收器(Oreo)

时间:2019-05-29 16:14:53

标签: java android kotlin

我的Android应用的targetdk版本为28,而我一直在阅读广播接收器版本27和更高版本的限制。话虽这么说,但我一直在尝试使用广播接收器打开和关闭蓝牙。打开该应用程序后,它的工作原理还不错,但是当我从最近使用的应用程序中清除它时,我不再收到烤面包和日志消息。我只是不确定即使没有打开应用程序也如何保持接收机运行。 (我从主要活动中删除了所有不必要的代码)

Android Manifest.xml

<uses-permission android:name="android.permission.BLUETOOTH"/>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service android:name=".NotificationsMessagingService">
            <intent-filter android:priority="1">
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".BReceivers" android:exported="true" android:enabled="true">
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
            </intent-filter>
        </receiver>
    </application>

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
}

BReceivers.kt

import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast

class BReceivers : BroadcastReceiver() {
    companion object {
        const val TAG = "Bluetoooth"
    }

    override fun onReceive(context: Context?, intent: Intent?) {

        if (intent?.action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            when(intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
                BluetoothAdapter.STATE_OFF -> Log.d(TAG, "Bluetooth is OFF")
                BluetoothAdapter.STATE_TURNING_OFF ->  Toast.makeText(context, "Bluetooth is turning off", Toast.LENGTH_LONG).show()
                BluetoothAdapter.STATE_ON ->  Log.d(TAG, "Bluetooth is ON")
                BluetoothAdapter.STATE_TURNING_ON ->  Toast.makeText(context, "Bluetooth is turning ON", Toast.LENGTH_LONG).show()
            }
        }

    }

}

0 个答案:

没有答案