带有图标的永久通知和“点按即可停止” [ANDROID STUDIO]

时间:2019-03-28 05:56:12

标签: java android build notifications android-notifications

我是Android Studio的新手,我一直在遵循一个教程来创建(看似)简单的跟踪应用程序。该应用程序运行正常,但是我无法在屏幕上保持持久通知(这很重要),它根本不显示任何内容。它应该在应用程序启动时与图标(我认为图标做得很好)一起显示,然后在点击时消失(应用程序关闭)。我在代码中找不到任何错误,但正如我所说,我是新手,所以我可能缺少了一些东西,谢谢:)

public void onCreate() {
    super.onCreate();
    buildNotification();
}

private void buildNotification() {
//Create the persistent notification//
String stop = "stop";
registerReceiver(stopReceiver, new IntentFilter(stop));
PendingIntent broadcastIntent = PendingIntent.getBroadcast(
this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);

// Create the persistent notification//
     Notification.Builder builder = new Notification.Builder(this)
             .setContentTitle(getString(R.string.app_name))
             .setContentText(getString(R.string.tracking_enabled_notif))

//Make this notification ongoing so it can’t be dismissed by the user//

.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.tracking_enabled);
 startForeground(1, builder.build());
 }

protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {

//Unregister the BroadcastReceiver when the notification is tapped//

unregisterReceiver(stopReceiver);

//Stop the Service//

stopSelf();
}
};

0 个答案:

没有答案