如何解决 Android 8 通知 Notification 不显示的问题

皮康龙发布

Android 8 以后需要给通知加个 channel 才能正常显示。示例代码如下:

package cn.edu.njupt.notificationtest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendNotice = (Button) findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_notice:
                String id = "channel_001";
                String name = "name";
                NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
                NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                Notification notification = new Notification.Builder(MainActivity.this)
                        .setChannelId(id)
                        .setContentTitle("This is content title")
                        .setContentText("This is content text")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .build();
                manager.notify(1, notification);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "2", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}
分类: 未分类

0 条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注