Android in-depth understanding of android onNewIntent pendingIntent

pendingIntent literal meaning: waiting, undecided Intent.
  pendingIntent objects, a method to use a static class:

      getActivity(Context, int, Intent, int)------->跳转到一个activity组件、

    getBroadcast(Context, int, Intent, int)------>打开一个广播组件

    getService(Context, int, Intent, int)-------->打开一个服务组件。

  Intent correspond to the behavior of three and four parameters, the more important things first and third, followed by the fourth and second. We can see, to get the object, you must pass a Intent as a parameter, there must be context as a parameter.

  pendingIntent is a special kind of Intent. The main difference is Intent executed immediately, while the execution pendingIntent not immediate. pendingIntent operation is substantially performed operation parameter passed in the Intent, but using the object to perform an operation pendingIntent it contains Intent is required to meet certain conditions.
Examples of primary and local use: sending notification, and performs transmission of a short message alarm AlarmManager Notificatio SmsManager the like.
English meaning intent intention, pending represent about to happen or come. 
This class is used to handle PendingIntent things about to happen. For example, in the notification Notification page for jumping in, but not jump right away. 

  Intent is a timely start, activity intent with where vanishes. 
PendingIntent can be seen as packaging intent is usually to get an instance of pendingintent by getActivity, getBroadcast, getService, current activity and intent can not start right away it contains, but when performed outside pendingintent, calling the intent. Precisely because pendingintent is saved in the current Context App, giving it the ability App outside, so that the external current App App can be the same as in the implementation of pendingintent of Intent, even if at the time of execution of the current App does not exist, but also through the presence of pendingintent implementation of the same in the Context Intent. Further processing operations may also be performed after the intent. And alermanger and notificationmanager often used together. 
Intent is generally used Activity, data transfer between Sercvice, BroadcastReceiver, and Pendingintent, generally used in Notification, intent can be understood as deferred execution, PendingIntent Intent is a package. 

Android status bar notification (Notification)

  If you need to see the message, you can drag the status bar to the bottom of the screen to view the message.

step:

  1 get notification manager NotificationManager, it is also a system service

  2 establishment notification Notification notification = new Notification (icon, null, when);

  3 is a new notification setting parameter (such as sound, vibration, flashing lights )

  4 added a new notification to the notification manager

Code to send the following message:

  // Get the Notification Manager

  NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)

  int icon = android.R.drawable.stat_notify_chat;

  long when = System.currentTimeMillis (); // time of notification of the occurrence of the current system time

  Notification notification = new Notification (icon, null, when); // create a new notification, the first parameter as an icon , and the second parameter is the short title prompt , the third at the time of notification

  notification.defaults = Notification.DEFAULT_SOUND; // default sound issue

  notification.flags | = Notification.FLAG_AUTO_CANCEL; // clicks automatically cleared after notification notice

  Intent openintent = new Intent(this, OtherActivity.class);

  ContentIntent = PendingIntent.getActivity the PendingIntent (the this, 0, openintent, 0); / / will be sent to the system when the click message openintent intent

  notification.setLatestEventInfo (this, "title ", "I am content ", contentIntent); // setLatestEventInfo expressed settings click on the notification event

  mNotificationManager.notify (0, notification); // first parameter uniquely identifies the custom notifications

  Focus is on the last parameter setLatestEventInfo () method! ! ! ! It is a PendingIntent !!!!!!!!!

  Used here to PendingIntent (pend intention is undetermined and uncertain meaning )

  PendingIntent can be seen as a package of Intent. PendingIntent information is mainly held by its package of Intent and the current Application of Context. Precisely because PendingIntent is stored in the current Application of Context, giving it his program to be executed with a capacity of Intent, even when executing the current Application does not exist, but also through the presence of PendingIntent in the Context still perform Intent.

 

Copy the code
Private void showNotify. 1 () {    
 2 the Notification Notice the Notification new new = ();    
 . 3 notice.icon = R.drawable.icon;    
 . 4 notice.tickerText = "You have a new message";    
 . 5 notice.defaults = Notification.DEFAULT_SOUND;    
 6 notice.when = 10L;    
 after 7 // 100 ms delay, the shock 250 ms, 100 ms pause, another 500 ms shock      
 8 //notice.vibrate = new long [] { 100, 250, 100, 500}; error ?   
 9 //notice.setLatestEventInfo(this, "notification", "friends meeting", PendingIntent.getActivity (the this, 0, null, 0));    
10 notice.setLatestEventInfo (the this, "notification", "friends meeting", PendingIntent. getActivity (this, 0, new Intent (this, Activity2.class), 0)); // page is about to jump, not the jump    
. 11 = the NotificationManager Manager (the NotificationManager) the getSystemService (this.NOTIFICATION_SERVICE);    
12 is manager.notify (0, Notice);    
13 is}  
Copy the code
Copy the code
Private void showNotify. 1 () {   
 2 the Notification Notice the Notification new new = ();   
 . 3 notice.icon = R.drawable.icon;   
 . 4 notice.tickerText = "You have a new message";   
 . 5 notice.defaults = Notification.DEFAULT_SOUND;   
 6 notice.when = 10L;   
 after 7 // 100 ms delay, the shock 250 ms, 100 ms pause, another 500 ms shock     
 8 //notice.vibrate = new long [] { 100, 250, 100, 500}; error ?  
 9 //notice.setLatestEventInfo(this, "notification", "friends meeting", PendingIntent.getActivity (the this, 0, null, 0));   
10 notice.setLatestEventInfo (the this, "notification", "friends meeting", PendingIntent. getActivity (this, 0, new Intent (this, Activity2.class), 0)); // page is about to jump, not the jump  
= The NotificationManager Manager. 11 (the NotificationManager) the getSystemService (this.NOTIFICATION_SERVICE);   
12 is manager.notify (0, Notice);   
13 is}  
Copy the code
Copy the code
1 1. GSM network messages transmitted Android Example 
 2 
 . 3 the Java Code 
 4 String msg = "Hello, beautiful";    
 . 5 Number String = "135 **** 6784";    
 . 6 SmsManager SmsManager.getDefault SMS = ();    
 . 7    
 . 8 PI = PendingIntent.getBroadcast the PendingIntent (SmsActivity.this, 0, the Intent new new (...), 0);    
 . 9 sms.sendTextMessage (Number, null, MSG, PI, null);    
10 Toast.makeText (SmsActivity.this, " send success ", Toast.LENGHT_LONG) .show ();  
Copy the code
Copy the code
1 String msg ="你好,美女";  
2 String number = "135****6784";  
3 SmsManager sms = SmsManager.getDefault();  
4   
5 PendingIntent pi = PendingIntent.getBroadcast(SmsActivity.this,0,new Intent(...),0);  
6 sms.sendTextMessage(number, null, msg, pi, null);  
7 Toast.makeText(SmsActivity.this,"发送成功",Toast.LENGHT_LONG).show(); 
Copy the code

Code explanation 
      PendingIntent is a description of Intent, we can use that description to other programs, other programs based on this description do what you do in other arrangements later time (By giving a PendingIntent to another application , you are granting it the right to perform the operation you have specified as if the other application was yourself, PendingIntent represents the equivalent of Intent). In this case another program is a program to send text messages, send text messages after the success of intent should broadcasted. 
      Function SmsManager.sendTextMessage (String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent) parameters explained: 
      1) PendingIntent sentIntent: When a message is issued, successful intent will be described sendIntent its internal broadcast out, or produce error correction code and by android.app.PendingIntent.OnFinished, the best parameter is not empty, otherwise there is a potential problem of wasted resources; 
      2) PendingIntent deliveryIntent: when PendingIntent broadcast the message has been delivered to the recipient conducted . 
      View PendingIntent class can see many of the Send function is PendingIntent performing related operations have been given.

A good example of PendingIntent:

 

Examples messaging system method for transmitting messages SmsManager of:

  sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);

  The first argument: destinationAddress mobile phone number

  The second parameter: scAddress SMS center number is usually set to null

  The third argument: text message content

  The fourth parameter: sentIntent determine whether the message is sent successfully, if you do not have a SIM card, or network outage, you can use this to determine itent. Note emphasized that whether the action "send" success. So as to whether they'll get a different matter

  The fifth parameter: deliveryIntent time when SMS to the recipient, will receive this deliveryIntent. That highlighted the results of the "send"

  That is the "SMS sent successfully " and "the other party to receive this message " will activate  sentIntent and deliveryIntent two Intent. This is equivalent to delay the execution of Intent


  Two examples above can be understood, Intent PendingIntent that can perform under certain conditions, it is compared to the advantage of their own Intent carries the Context object, so that he would not have to rely on a certain activity can exist.

//////////////////////////////////////////////////////////////////////////////////////////////

The role of PendingIntent and Examples , and the difference between the Intent and

1, PendingIntent role

  According to the literal meaning that this is a delay of intent, mainly used in the event of a complete implementation of specific Action . PendingIntent contains Intent and Context, so even if your program ends Intent, PendingIntent still valid, can be used in other programs.
Commonly used in the notification bar and SMS systems.

  PendingIntent generally as an argument to an instance, the complete automatic execution PendingIntent Action In this instance after an operation, may also be performed manually by the PendingIntent send function, and may be provided in OnFinished send function indicating the success of the operation performed after the send .

2, PendingIntent Examples

a. the system notification bar

Copy the code
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis() + 2000;
Notification n = new Notification(icon, "通知栏demo提醒", when);
n.defaults = Notification.DEFAULT_SOUND;
n.flags |= Notification.FLAG_AUTO_CANCEL;

Intent openintent = new Intent(this, DemoList.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, openintent, PendingIntent.FLAG_CANCEL_CURRENT);
n.setLatestEventInfo(this, "通知栏demo提醒title", "通知栏demo提醒text", pi);
nm.notify(0, n);
Copy the code

  setLatestEventInfo expressed settings click on the notification event

b. Examples messaging system

  When more than two PendingIntent sentPI and deliveredPI were sent successfully and the other party will accept the success in the message is broadcast

3, the difference of Intent and PendingIntent

  a. Intent is for immediate use, and PendingIntent can wait until after the incident triggered, can PendingIntent the Cancel
  b. Intent is terminated after the end of the program, while PendingIntent at the end of the program still valid
  c. PendingIntent comes Context, and in need of a Intent a run within the Context
  D. in the original task runs in the Intent, PendingIntent run on the new task of

PendingIntent used to describe the Intent and the final act. 
  You can getActivity (Context context, int requestCode, Intent intent, int flags) from the system to obtain a series of methods used to start an Activity PendingIntent objects,

  By getService (Context context, int requestCode, Intent intent, int flags) to obtain a method for initiating a Service object from the system of PendingIntent

  By getBroadcast (Context context, int requestCode, Intent intent, int flags) method for obtaining a broadcast Intent BroadcastReceiver from the target system PendingIntent

  PendingIntent return can be submitted to other applications, and then continue processing. Here, then you can only deal with Intent and its final act PendingIntent described later.

  When you put PendingIntent submitted for processing to another program, PendingIntent PendingIntent still has permission to have the original program (with the same permissions and identity). When you get a PendingIntent from the system, we must be very careful job. For example, generally, if the Intent destination is your own component (Activity / Service / BroadcastReceiver), then you'd better show using the name of the specified destination component in the Intent way to ensure Intent eventually sent to the destination, otherwise it may end Intent I do not know where to send the. A PendingIntent is a token Android system (node, this should be a Linux or C \ C ++ language) of an object reference, which describes some of the data (here will be used to retrieve these data describe the behavior of Intent and the final ).

  This means that even PendingIntent original end of the process, then, PendingIntent itself is still there, (the other being submitted to the program PendingIntent) may continue to be used in other processes. If I was in a PendingIntent extracted from the system, but the system has a peer and PendingInent PendingIntent you describe, then the system will directly return and in fact the same token PendingIntent of PendingIntent, rather than a new token and PendingIntent. However, when you extract from PendingIntent, by FLAG_CANCEL_CURRENT parameters, so that the old PendingIntent first-cancel () away, it is the new so obtained pendingInten and its token of the.

  By FLAG_UPDATE_CURRENT parameters, you can make new Intent Intent object data will be updated before the PendingIntent, such as updating the Intent of Extras. In addition, we can also call cancel PendingIntent in the original process PendingIntent in () to remove it out of the system.

 

onResume () method

Since the operation Bactivity, affecting the data Aactivity, so go back to A when A can require a refresh operation.
But the default jump back in time, A interface or the last one.

Solution: Rewrite the onResume Aactivity () method, refresh operation in onResume () in terms. Because the life cycle model of activity, when activity recovered, onResume () method is called, so this is a good opportunity to refresh.

android onNewIntent

When Android application development, from one Activity to start another Activity and pass some data to the new Activity is very simple, but when you need to make Activity running in the background and foreground back pass some data might exist a little small problem.

First, by default, even when you are already an identical Activity is running, the system will create a new Activity instance via Intent to start an Activity time, and displayed. Activity Example In order to prevent multiple times, we need in AndroidManifest.xml activity of loading configuration (the launchMode) to achieve a single-tasking mode, as follows:


1 <activity android:label="@string/app_name" android:launchmode="singleTask"android:name="Activity1">

2 </activity>


launchMode to singleTask time, by Intent to start a Activity, if the system already exists one instance, the system sends a request to this instance, but this time, the system will no longer call onCreate Normally we deal with the requested data method, it calls onNewIntent method, as follows:


1 protected void onNewIntent(Intent intent) {

2   super.onNewIntent(intent);

3   setIntent(intent);//must store the new intent unless getIntent() will return the old one

4   processExtraData();

5 }


Do not forget that you may be ready to kill Activity running in the background, if this happens, then the system will call onCreate method, without calling onNewIntent method, a good solution is to call the same data processing methods in onCreate and onNewIntent the method, as follows:


01 public void onCreate(Bundle savedInstanceState) {

02   super.onCreate(savedInstanceState);

03   setContentView(R.layout.main);

04   processExtraData();

05 }

06  

07 protected void onNewIntent(Intent intent) {

08   super.onNewIntent(intent);

09   setIntent(intent);//must store the new intent unless getIntent() will return the old one

10   processExtraData()

11 }

12  

13 private void processExtraData(){

14   Intent intent = getIntent();

15   //use the data received here

16 }

 

Guess you like

Origin www.cnblogs.com/Alex80/p/11519886.html