0
我正在寫一個連接到Arduino藍牙設備的應用程序。目標是讓Android用戶在手機離開Arduino的範圍時收到推送通知。無論應用程序是否在前臺,都應該發生這種情況。爲此,我目前在Android Manifest中使用BroadcastReceiver。但是,我沒有收到任何此類通知。Android - 檢查藍牙連接丟失嗎?
這裏是實現廣播接收器接收器類:
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
pushNotification(context);
}
}
}
public void pushNotification(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setAutoCancel(true);
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("This is a notification!");
builder.setContentText("This is the notification text!");
builder.setSubText("This is the notification subtext!");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
}
而且AndroidManifest.xml中
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<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=".Receiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
我相當肯定,問題出在我用我的邏輯常量。但是,我不確定我應該使用哪些。實際上,當Android藍牙發生任何狀態變化時,接收器會被激活,但我只想在連接丟失時發出通知,這可能與Android藍牙接收器的狀態更改沒有任何關係。 我應該如何確保在這些條件下調用pushNotification()?
可能的[Android的重複:關閉/丟失藍牙連接或文件接收 - >做某事](http://stackoverflow.com/questions/2905240/android-shut-down-loss-of-bluetooth-connection - 或文件的RECE香港專業教育學院-DO-事端) –