Android technology-Notification Activity

Source: Internet
Author: User

Android technology essence-Notification activityconfigurications
Anyone who has experience in Android development should know that Notification is a normal UI that can be displayed to the user application. The icon that appears in the notification area when the system sends a notification. You can open notification drawer to view the details of the notification. At the same time, the mobile phone will have the following: 1. First, the status bar, the icon lasting in the notification area 2. Enable or flash the device's LED3, and remind the user through flashing backlight, playing sound or vibration




NotificationActivity code:The code function is to enable a task by clicking the button in the Activity. The message queue is inserted with a delay of 10 seconds to enable a notification!

package activitys;import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.Button;import android.widget.Toast;public class NotificationActivity extends Activity implements View.OnClickListener {private static final int NOTE_ID = 100;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);Button button = new Button(this);button.setText("Post New Notification");button.setOnClickListener(this);setContentView(button);}@Overridepublic void onClick(View v) {handler.postDelayed(task, 10000);Toast.makeText(this, "Notification will post in 10 seconds",Toast.LENGTH_SHORT).show();}private Handler handler = new Handler();private Runnable task = new Runnable() {@Overridepublic void run() {NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);Intent launchIntent = new Intent(getApplicationContext(),Test.class);PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);Notification note = new Notification(R.drawable.icon,"Something Happened", System.currentTimeMillis());note.setLatestEventInfo(getApplicationContext(), "Finished!","Click Here!", contentIntent);note.defaults |= Notification.DEFAULT_SOUND;note.flags |= Notification.FLAG_AUTO_CANCEL;manager.notify(NOTE_ID, note);}};}



PostDelayed (Runnable r, long delayMillis)
Delayed delayMillis inserts Runnable into message queue in milliseconds, and Runnable runs in the thread bound to handle. Post is to insert a Message Queue immediately. It runs only when the message queue processes the message.


PendingIntent
We know that Intent is started in time, and the intent disappears with the activity.
PendingIntent is the packaging of intent. Generally, the pendingintent instance pendingintent can be obtained through getActivity, getBroadcast, and getService, and the Context of the current App is saved in the PendingIntent instance, which gives the external App a capability, this allows the external App to execute the Intent in pendingintent like the current App. Even if the current App does not exist at the time of execution, it can still execute the Intent through the Context in pendingintent. You can also process operations performed by intent. It is often used with alermanger and icationicationmanager.
Intent is generally used to transmit data between activities, Sercvice, and BroadcastReceiver, while Pendingintent is generally used in Notification. It can be understood as a delayed execution intent, and PendingIntent is a packaging of Intent.
In short, PendingIntent is an Intent that can be executed under certain conditions. Compared with Intent, PendingIntent has its own Context object, so that it does not have to rely on an activity to exist.

Notification
NotificationPublic class Notification
Extends Object
Implements Parcelable

1. Create a Notification
Use icationicationmanager's notify (int, Notification) method to start Notification.
The first parameter uniquely identifies the Notification, and the second parameter is the Notification object.
2. Update Notification
Call the setLatestEventInfo method of Notification to update the content, and then call icationicationmanager's notify () method. (For details, refer to the following instance)
3. Delete Notification
Use the cancel (int) method of icationicationmanager to clear a notification. The parameter is the unique ID of Notification.
You can also clear all notifications in the status bar through cancelAll.
4. Notification Settings (vibration, ringtones, etc)

Notification sample code:
// Create a new status bar notification baseNF = newNotification (); // set the icon baseNF of the notification displayed in the status bar. icon = R. drawable. icon; // The baseNF content displayed in the status bar during notification. tickerText = "YouclickedBaseNF! "; // Default notification parameters: DEFAULT_SOUND, DEFAULT_VIBRATE, and DEFAULT_LIGHTS. // if you want to use all the default values, use DEFAULT_ALL. // The default baseNF is used here. defaults = Notification. DEFAULT_SOUND; // The second parameter: the message title expandedmessagetitle displayed in the drop-down status bar // The third parameter: the message content expandedmessagetext displayed in the drop-down status bar // The fourth parameter: when you click this notification, the execution page jumps to baseNF. setLatestEventInfo (Lesson_10.this, "Title01", "Content01", pd); // send a status bar notification // ThefirstparameteristheuniqueIDfortheNotification // andthesecondisthenotificationicationobject. nm. Y (icationication_id_base, baseNF );


Add Notification sound:
1. If you want to use the default sound, you only need to use the default sound.
baseNF.defaults=Notification.DEFAULT_SOUND; 

2. If you want to use custom sound, you need to use sound. As follows:
notification.sound=Uri.parse("file:///sdcard/notification/ringer.mp3"); 

3. If you want to use the built-in ringtone, you can:
notification.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI,"6"); 

(If both default and sound appear, the default ringtone is used if sound is invalid. )
4. By default, the playing of the notification sounds ends once. If you want to play audio cyclically, you need to add FLAG_INSISTENT to the flags parameter. In this way, the voice will not end until the user responds, such as the drop-down status bar.
notification.flags|=notification.FLAG_INSISTENT; 

Add vibration in Notification:
1. Default vibration mode.
notification.defaults|=Notification.DEFAULT_VIBRATE; 

2. Define the vibration form by yourself. A Long array is needed here.
long[]vibrate={0,100,200,300}; notification.vibrate=vibrate; 
In the Long array, the first parameter is the waiting time before the vibration starts, the second parameter is the first vibration time, the third parameter is the second vibration time, and so on, you can specify the length of an array. But using this method, there is no way to achieve repeated vibration.
Similarly, if both default and vibrate appear, the default format is used.

Note: add permissions.:

Add flash Notification:
1. Default Lighting
notification.defaults|=Notification.DEFAULT_LIGHTS; 


2. Custom lighting:
notification.ledARGB=0xff00ff00; notification.ledOnMS=300; notification.ledOffMS=1000; notification.flags|=Notification.FLAG_SHOW_LIGHTS; 
LedARGB indicates the light color, ledOnMS light duration, and ledOffMS dark time.


Other useful settings for Notification:
Flags: Notification. FLAG_INSISTENT; // infinite loop of sound and vibration until the user responds to Notification. FLAG_AUTO_CANCEL; // The Notification disappears automatically after the Notification is clicked. FLAG_NO_CLEAR; // when you click 'clear', the notification is not Clear (QQ notifications cannot be cleared, that is, this // custom drop-down view is used, such as when downloading software, the progress bar. Icationicationnotification = newNotification (); notification. icon = R. drawable. icon; notification. tickerText = "Custom! "; RemoteViewscontentView = newRemoteViews (getPackageName (), R. layout. custom); contentView. setImageViewResource (R. id. image, R. drawable. icon); contentView. setTextViewText (R. id. text, "Hello, thismessageisinacustompandedview"); notification. contentView = contentView; // when using a custom drop-down view, you do not need to call the setLatestEventInfo () method // but you must define the contentIntent notification. contentIntent = pd; nm. Y (3, notification );



Use custom Notification

To create a custom Notification, you can use RemoteViews. To define your own extended message, first initialize a RemoteViews object, pass it to the contentView field of Notification, and then pass PendingIntent to the contentIntent field. The following sample code is a complete step:

1. Create a custom message layout view. xml

  
  
   
   
  


// 2. Use the RemoteViews method in the program code to define the image and text. Upload the RemoteViews object to the contentView field.

RemoteViews contentView = new RemoteViews (getPackageName (), R. layout. view); contentView. setImageViewResource (R. id. image, R. drawable. icon); contentView. setTextViewText (R. id. text, "Hello, this message is in a custom expanded view"); notification. contentView = contentView; // 3. Define an Intent for the contentIntent field of Notification (note that the setLatestEventInfo () method is not required to use the custom View) Intent icationicationintent = new Intent (this, Main. class); PendingIntent contentIntent = PendingIntent. getActivity (this, 0, icationicationintent, 0); notification. contentIntent = contentIntent;


// 4. Send a notification

Micationicationmanager. Y (2, notification); // The following is all the sample code // create a icationicationmanager reference String ns = Context. NOTIFICATION_SERVICE; NotificationManager micationicationmanager = (NotificationManager) getSystemService (ns); // defines the attributes of Notification, int icon = R. drawable. icon; // notification icon CharSequence tickerText = "Hello"; // notification text displayed in the status bar prompt long when = System. currentTimeMillis (); // the time when a notification is generated. It is displayed in the Notification information. // The above attributes initialize noicationnotification notification = new Notification (icon, tickerText, when ); remoteViews contentView = new RemoteViews (getPackageName (), R. layout. view); contentView. setImageViewResource (R. id. image, R. drawable. iconempty); contentView. setTextViewText (R. id. text, "Hello, this is JC"); notification. contentView = contentView; Intent notificationIntent = new Intent (this, Main. class); PendingIntent contentIntent = PendingIntent. getActivity (this, 0, icationicationintent, 0); notification. contentIntent = contentIntent; // transmits the Notification to icationicationmanagermnotificationmanager. Y (0, notification );


2014.1.22

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.