繁体   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