Your experience on this site will be improved by allowing cookies
To facilitate a piece of short, but timely information about the action happening in the application, even when the application is not running, Android Notification is used in an application. Icon, title, and some amount of the content text can be displayed by the Android notification.
The NotificationCompat.Builder object is used to set the properties of the Android notification. There are several notification properties. Some of these are:
In the below example, we are using the Android Notification to create a notification message. This message on clicking launches another activity.
activity_main.xml:
In the activity_main.xml file, we will write the below code.
Code:
MainActivity.java:
In the MainActivity.java file, we will write the code to call the addNotification() method, on clicking the button. Here, we will implement the NotificationCompat.Builder object to set the notification properties. To display the notification, we are using the NotificationManager.notify() method. To call another activity (NotificationView.java) on taping the notification, the Intent class is used.
Code:
package com.example.radioapp; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnNotify = (Button)findViewById(R.id.btnShow); btnNotify.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Implement inbox style notification NotificationCompat.InboxStyle iStyle = new NotificationCompat.InboxStyle(); iStyle.addLine("Hello..."); iStyle.addLine("Hi....."); iStyle.addLine("GoodMorning...."); iStyle.addLine("Going...."); iStyle.addLine("Have a...."); iStyle.setSummaryText("+2 more"); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("You have new Messages!!") .setStyle(iStyle); // Set the intent to fire when the user taps on notification. Intent resultIntent = new Intent(MainActivity.this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent, 0); mBuilder.setContentIntent(pendingIntent); // Sets an ID for the notification int mNotificationId = 001; NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // It will display the notification in notification bar notificationManager.notify(mNotificationId, mBuilder.build()); } }); } } |
0 comments