我正在为我的拼贴画做我的最后一个项目,我一直在寻找 android 的蓝牙通知代码。我需要代码来在我的蓝牙打开或关闭时通知我
问问题
784 次
2 回答
2
OK then do it like that when you bluetooth is on or off
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_FOUND.equals(action)) {
int icon = R.drawable.nishansahib1; // icon from resources
CharSequence tickerText = "SatShreeAkal"; // ticker-text
long when = System.currentTimeMillis(); // notification time
//Context context = getApplicationContext(); // application Context
CharSequence contentTitle = ""; // message title
//
CharSequence contentText= "YPUR BLUETOOTH IS ON OR OFF"; // message text
final int NOTIF_ID = 1234;
Intent notificationIntent = new Intent(context, your classname);//if u want to call a class
notificationIntent.putExtra("DISPLAY",contentText);//if u want to pass intent
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
NotificationManager notofManager = (NotificationManager)context. getSystemService(Context.NOTIFICATION_SERVICE);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.defaults = Notification.DEFAULT_SOUND;
notofManager.notify(NOTIF_ID,notification);
}
于 2012-07-06T07:01:29.770 回答
1
您需要在代码中添加广播接收器,以便在您的活动类中打开或关闭蓝牙后接收。供你参考 :
public void onCreate() {
...
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
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_FOUND.equals(action)) {
... //Device found
}
else if (BluetoothAdapter.ACTION_ACL_CONNECTED.equals(action)) {
... //Device is now connected
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
... //Done searching
}
else if (BluetoothAdapter.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
... //Device is about to disconnect
}
else if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) {
... //Device has disconnected
}
}
于 2012-07-06T06:23:53.783 回答