我目前正在开发一个 Android 应用程序,而蓝牙对于该应用程序来说是必不可少的。我运行后台服务。后台服务做的一件事是检查蓝牙是否启用。如果不是,将会有新的通知。当您单击它时,我希望启用蓝牙并且用户能够恢复他正在做的任何事情。就是这样。
现在,当我点击通知时,它会启动一个新的 Activity 和一个新的 View 并启用蓝牙。我不希望那个新观点出现在那里。我在启用蓝牙后尝试使用 finish(),但这让我回到了我的应用程序中的最后一个 Activity ,而不是我在按下通知之前使用的应用程序。
所以我正在阅读一个新闻应用程序,点击通知和蓝牙启用,但也将我带到我自己的应用程序而不是我正在使用的新闻应用程序。
这是正在发送的新通知:
if (!mBluetoothAdapter.isEnabled())
{
NotificationCompat.Builder mBuilder;
mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.bluetooth)
.setContentTitle("Bluetooth disabled")
.setContentText("Click here to enable bluetooth")
.setOngoing(true);
Intent resultIntent = new Intent(this, TurnOnBluetooth.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
int mNotificationId = 159;
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
这是 TurnOnBluetooth.java 中的 onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_turn_on_bluetooth);
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
mNotifyMgr.cancel(159);
finish();
}
请注意,我注释了 setContentView();因为我不想要新 View ,所以我只想打开蓝牙并在之后摆脱通知,仅此而已。 finish() 将我带回我的应用程序,而不是我在按下通知之前使用的应用程序。我怎样才能做到这一点?
最佳答案
我自己解决了这个问题。我没有开始新的 Activity,而是使用了一个可以解决问题的 broadcastreceiver。
广播接收者的onReceive():
public void onReceive(Context context, Intent intent) {
NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
mNotifyMgr.cancel(159);
}
list 中的接收器:
<receiver
android:name="com.novioscan.service.NotificationReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="NotService"/>
</intent-filter>
</receiver>
新通知声明:
if(!mBluetoothAdapter.isEnabled()){
NotificationCompat.Builder mBuilder;
mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.bluetooth)
.setContentTitle("Bluetooth disabled")
.setContentText("Click here to enable bluetooth")
.setOngoing(true);
// Intent resultIntent = new Intent(this, TurnOnBluetooth.class);
Intent resultIntent = new Intent("NotService");
//resultIntent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
// Sets an ID for the notification
int mNotificationId = 159;
PendingIntent resultPendingIntent =
PendingIntent.getBroadcast(
this,
0,
resultIntent,
0
);
mBuilder.setContentIntent(resultPendingIntent);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
现在一切正常:)
关于android - 通过通知按钮打开蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26716101/