簡體   English   中英

看不到通知 - android studio

[英]can't see a notification - android studio

我嘗試發出通知,但單擊按鈕時沒有通知,也沒有錯誤。 我啟用了來自電話設置的通知。

我的代碼


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class notification_page extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_page);
       // Button notify = findViewById(R.id.notify);


    }


    NotificationManager manager;
    int id =0;


    public void notify(View view) {

        NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);
        nBuilder.setContentTitle("Hello").setContentText("Notificaction!!").setSmallIcon(R.drawable.common_google_signin_btn_icon_dark);
        manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(id,nBuilder.build());
        id++;

    }

    public void cancel(View view) {
manager.cancelAll();
    }
}

XML 按鈕android:onClick="notify"

並且 Logcat 中沒有錯誤

首先,您必須創建通知通道:

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("1000", "channel_name", importance);
        channel.setDescription("channel_description");
        channel.setSound(null, null);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

NotificationManager更改為:

NotificationManagerCompat manager;

然后像這樣修改你的notify() function :

public void notify(View view) {
    createNotificationChannel(); //don't forget to create the channel
    NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, "1000"); //channelId should be same as the one created above
    nBuilder.setContentTitle("Hello").setContentText("Notificaction!!").setSmallIcon(R.drawable.common_google_signin_btn_icon_dark);
    manager = NotificationManagerCompat.from(getApplicationContext());
    manager.notify(id, nBuilder.build());
    id++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM