Three methods of using notification bar notification in Android (short content, long content, picture notification)

I. Introduction:

       Notifications are very common in Android. You will often see notifications from an app appear in the notification bar, or appear in the form of banners at the top of the phone screen, or even make the phone vibrate, ring the ringtone, and make the indicator light flash. . Today, I learned how to use notifications and write a note.

Second, the program realization effect diagram:

1. Short content notification (only one line of text will be displayed, if there is more, it will be omitted with ellipsis), and it will be displayed on the screen in the form of a banner


2. Notification in the form of long content (the notification content can be displayed in multiple lines)


3. Notifications in the form of pictures


3. Implementation process and code:

1. First create a new project. We put three buttons in the layout file to imitate and initiate three different notifications (1. Short content, 2. Long content, 3. Notification in the form of pictures) The codes are as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
        android:id="@+id/mBt_short"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notification1"
        android:textAllCaps="false"
        android:layout_gravity="center_horizontal"
       />
    <Button
        android:id="@+id/mBt_long"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notification2"
        android:textAllCaps="false"
        android:layout_gravity="center_horizontal"
        />
    <Button
        android:id="@+id/mBt_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notification3"
        android:textAllCaps="false"
        android:layout_gravity="center_horizontal"
        />
</LinearLayout>

This layout file is very simple. There are only three buttons and nothing else. It is mainly used to imitate the application to initiate notifications.

2. When we click on a notification, it should jump to an Activity, so create a new Activity called NotificationActivity, and let it jump to this Activity when we click on a notification. Of course, the Activity to which each different notification is clicked is generally different. For the sake of simplicity, I let them all jump to this Activity. Its code Hull layout is as follows:

public class NotificationActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView ( R.layout.activity_notifacation );
        //After clicking the notification, you can also cancel the notification with the following methods
        NotificationManager  manager = (NotificationManager)
                getSystemService ( NOTIFICATION_SERVICE );
        manager.cancel ( 1 );//The parameter is the ID of the notification to cancel
        // The following code is to destroy the previous Activity after jumping over
        //mainActivity is defined in MainActivity
       // MainActivity.mainActivity.finish();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This is notification1 Activity"
        android:textSize="20sp"
        android:gravity="center"
        android:layout_marginTop="10dp"/>
</LinearLayout>

This Activity has nothing to say, the main thing is to let it jump to this Activity and it will be OK.

3. The following is the most important and important code of MianActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button mBt_short;
    private Button mBt_long;
    private Button mBt_image;
    public static MainActivity mainActivity;//Define global variables
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView ( R.layout.activity_main );
        mBt_short = findViewById ( R.id.mBt_short );
        mBt_long = findViewById ( R.id.mBt_long );
        mBt_image = findViewById ( R.id.mBt_image );
        mBt_short.setOnClickListener ( this );
        mBt_long.setOnClickListener ( this );
        mBt_image.setOnClickListener ( this );
        mainActivity = this;//Assign the current Activity to it, which can be called in other Activity
    }
    @Override
    public void onClick(View view) {
        switch (view.getId ()){
            case R.id.mBt_short:
                //Add a click to jump Activity to the notification
                Intent intent =  new Intent(MainActivity.this,NotificationActivity.class);
                PendingIntent pi = PendingIntent.getActivity ( this,0,intent,0 );
                //Get the NotificationManager instance
                NotificationManager manager = (NotificationManager)
                        getSystemService ( NOTIFICATION_SERVICE );
                //Create notification object
                Notification notification = new NotificationCompat.Builder(this)
                        //Set the notification object
                        //priority is to set the importance of the notification, set as follows,
                        // The notification will appear as a banner at the top of the screen
                        .setPriority ( NotificationCompat.PRIORITY_MAX )
                        .setContentTitle("A short notification")
                        .setContentText ( "Only one line will be displayed," +
                                "Too long is an ellipsis")
                        .setAutoCancel ( true )//Click the notification and disappear from the notification bar
                        .setWhen ( System.currentTimeMillis () )
                        .setSmallIcon ( R.mipmap.ic_launcher )
                        .setLargeIcon ( BitmapFactory.decodeResource
                                ( getResources (),R.mipmap.ic_launcher ) )
                        .setContentIntent ( pi )//Pass in the previously created pi
                        .setVibrate ( new long[]{0,1000,1000,1000,} )//Set vibration
                        .setLights ( Color.GREEN, 1000, 1000 )//Set the prompt light
                        //The following is the default effect set as notification (vibration, ringtone, prompt light)
                        //.setDefaults ( NotificationCompat.DEFAULT_ALL )
                        .build ();//All setup methods are called before the .build method
                manager.notify ( 1, notification );//where 1 is the ID of this notification
                break;
            case R.id.mBt_long:
                Intent intent2 =  new Intent(MainActivity.this,NotificationActivity.class);
                PendingIntent pi2 = PendingIntent.getActivity ( this,0,intent2,0 );
                NotificationManager manager2 = (NotificationManager)
                        getSystemService ( NOTIFICATION_SERVICE );
                Notification notification2 = new NotificationCompat.Builder ( this )
                        .setContentTitle("a long notification")
                        //When the notification content is too long to be displayed in one line, you can use setStyle
                        .setStyle ( new NotificationCompat.BigTextStyle().bigText(
                                "This is a very long notification message, too long to fit a normal notification message" +
                                        "Until now, only special notification forms can be used, as they are now." ) )
                        .setWhen ( System.currentTimeMillis () )
                        .setSmallIcon ( R.mipmap.ic_launcher )
                        .setLargeIcon ( BitmapFactory.decodeResource
                                ( getResources (),R.mipmap.ic_launcher ) )
                        .setAutoCancel ( true )
                        .setContentIntent ( pi2 )
                        .build ();
                manager2.notify (2,notification2 );
                break;
            case R.id.mBt_image:
                Intent intent3 =  new Intent(MainActivity.this,NotificationActivity.class);
                PendingIntent pi3 = PendingIntent.getActivity ( this,0,intent3,0 );
                NotificationManager manager3 = (NotificationManager)
                        getSystemService ( NOTIFICATION_SERVICE );
                Notification notification3 = new NotificationCompat.Builder ( this )
                        .setContentTitle("Notification for a picture")
                        //When the notification content is in the image form, setStyle is also used
                        .setStyle ( new NotificationCompat.BigPictureStyle ( ).
                                bigPicture ( BitmapFactory.decodeResource
                                        ( getResources (),R.drawable.big_image ) ))
                        .setWhen ( System.currentTimeMillis () )
                        .setSmallIcon ( R.mipmap.ic_launcher )
                        .setLargeIcon ( BitmapFactory.decodeResource
                                ( getResources (),R.mipmap.ic_launcher ) )
                        .setAutoCancel ( true )
                        .setContentIntent ( pi3 )
                        .build ();
                manager3.notify (3,notification3);
                break;
            default:
                break;
        }
    }
}
This one is a bit long, but not complicated. Mainly in the onClick(View view) method, different forms of notifications are set for the three buttons, so it seems a bit long. I have commented the code for creating notifications, so I won't go into too much detail here. In addition, a global variable mainActivity is defined and this is assigned to it, mainly to use it in NotificationActivity to destroy MainActivity. In fact, it doesn't matter if it is destroyed or not, so I commented it out.


Source code download



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325516874&siteId=291194637