先来看看效果
1.MainActivity.java ( android8.0开始引入了通知渠道的概念,也就是说每条通知都要属于一个对应的渠道,每个应用程序都考科一自由地创建当前应用拥有哪些通知渠道,但是这些通知渠道的控制权是掌握在用户手上的。
public class MainActivity extends Activity implements View.OnClickListener {
private Button sendNotice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendNotice = findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_notice:
//获取通知管理实例
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//8.0以后的通知渠道
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
NotificationChannel channel=new NotificationChannel("important","Important",NotificationManager.IMPORTANCE_HIGH);
assert manager != null;
manager.createNotificationChannel(channel);
}
//通知点击事项
Intent intent=new Intent(this,NotificationActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,0);
Notification notification= new NotificationCompat.Builder(this,"important")
.setContentTitle("收到一条通知")
.setContentText("你好")
.setSmallIcon(R.mipmap.ic_launcher)//通知图标
.setContentIntent(pendingIntent)//点击跳到通知详情
.setAutoCancel(true)//当点击通知后显示栏的通知不再显示
.build();
assert manager != null;
manager.notify(1,notification);
break;
default:
break;
}
}
}
2.activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/send_notice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send notice"
/>
</LinearLayout>
3.NotificationActivity.java
public class NotificationActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
}
}
4.activity_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NotificationActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="24sp"
android:text="这是通知的具体内容"/>
</RelativeLayout>