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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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;
}
}
}