![在这里插入图片描述](https://img-blog.csdnimg.cn/20210317110707296.gif)
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
public class NotificationActivity extends AppCompatActivity implements View.OnClickListener{
private Button btnSend;
private NotificationManager manager;
private Notification notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
btnSend = (Button) findViewById(R.id.btn_send);
btnSend.setOnClickListener(this);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
if(v.getId() == R.id.btn_send) {
if(manager.areNotificationsEnabled() == false) {
Intent notificationIntent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
notificationIntent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
notificationIntent.putExtra(Settings.EXTRA_CHANNEL_ID, getApplicationInfo().uid);
startActivity(notificationIntent);
} else {
NotificationChannel channel = new NotificationChannel("app002", "普通通知", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
Intent intent = new Intent(this, NetBroadcastActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, 0);
notification = new NotificationCompat.Builder(this, "default")
.setChannelId("app002")
.setContentTitle("hello")
.setContentText("start broadcast")
.setVibrate(new long[] {0, 1000, 1000, 1000})
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.happy))
.build();
manager.notify(1, notification);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".NotificationActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_send"
android:layout_gravity="center_horizontal"
android:text="发送通知"
android:textSize="17sp" />
</LinearLayout>