Source Code:https://github.com/HBU/AndroidTest/tree/master/NotificationHangUp
Android Studio 3.5
Gradle 5.4.1
Java 代码:
import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; 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; //Ref: https://blog.csdn.net/guolin_blog/article/details/79854070 郭霖 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void ClickMe(View view){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "007"; String channelName = "James Bond"; NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH); NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(notificationChannel); Notification notification = new NotificationCompat.Builder(this, "007") .setContentTitle("What is 5G ?") .setContentText("But before we get to the smart phones, let‘s simply figure out what 5G is.") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.berry) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.berry)) .setAutoCancel(true) .build(); notificationManager.notify(1, notification); } } }
布局文件:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity"> <Button android:id="@+id/button" android:layout_width="192dp" android:layout_height="104dp" android:text="Button" android:onClick="ClickMe" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.303" /> </androidx.constraintlayout.widget.ConstraintLayout>
效果图: