在蓝牙断开连接时显示通知 - Android

时间:2012-12-06 04:27:28

标签: android bluetooth notifications broadcastreceiver

如果蓝牙设备突然超出我的Android设备范围,我正在尝试创建一个向用户显示notification的程序。我目前有以下代码,但没有显示通知。

我想知道是否有可能我不应该使用ACTION_ACL_DISCONNECTED,因为我相信bluetooth堆栈会期望请求断开状态的数据包。我的要求声明蓝牙设备会在没有警告的情况下断开连接。

感谢您的帮助!

BluetoothNotification.java: //这是创建通知的位置。

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;


public class BluetoothNotification extends Activity
{
public static final int NOTIFICATION_ID = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /** Define configuration for our notification */
    int icon = R.drawable.logo;
    CharSequence tickerText = "This is a sample notification";
    long when = System.currentTimeMillis();
    Context context = getApplicationContext();
    CharSequence contentTitle = "Sample notification";
    CharSequence contentText = "This notification has been generated as a result of BT Disconnecting";
    Intent notificationIntent = new Intent(this, BluetoothNotification.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    /** Initialize the Notification using the above configuration */
    final Notification notification = new Notification(icon, tickerText, when);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

    /** Retrieve reference from NotificationManager */

    String ns = Context.NOTIFICATION_SERVICE;
    final NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);


    mNotificationManager.notify(NOTIFICATION_ID, notification);

    finish();
}    
}
来自OnCreate的

Snippet://位于Controls.java

IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
来自Controls.java的

片段:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
               //Device has disconnected
            NotificationManager nm = (NotificationManager) 
                    getSystemService(NOTIFICATION_SERVICE);
        }

    }

};

1 个答案:

答案 0 :(得分:0)

您的BroadCastReceiver与您的活动之间有什么联系?

不需要此活动,将所有内容都放在广播接收器中以显示通知。