The _android of switching effect before and after the application in Android development

Source: Internet
Author: User
Tags stub

Before introducing the program implementation, let's look at the basics of activities and tasks in Android.

As we all know, one activity can start another, even if it is defined in a different application, for example, if you want to show the user a map of information, there is already a task that can do this, So now all your activity needs to do is put the request information into a intent object and pass the intent object to StartActivity (), and the map can be displayed, but after the user presses the Back button, Your activity again appears on the screen.


For users, showing the activity of the map and your activity seems to be in an application, although they are defined in other applications and run in that process. Android puts your activity and borrowed activity into a task to maintain the user experience. Then the task is organized into a stack of interrelated activity, and the activity at the bottom of the stack is the task, usually the activity the user chooses in the Application Launcher. The activity at the top of the stack is one that is currently running activity--the user is interacting with.


When an activity initiates another activity, the newly initiated activity is pressed into the stack as a running activity. The old activity is still on the stack. When the user presses the back key, the running activity pop-up stack, the old activity resumes as the running activity. The stack contains objects, so if multiple objects of the same activity subclass are opened in a task-for example, multiple map browsers-the stack has a separate entry for each instance. The activity in the stack is not reordered and will only be ejected. A task is a stack of activity instances, not a class or element in a manifest file, so it is not possible to set the attributes of a task regardless of its activity, and all the attribute values of a task are set in the activity at the bottom. This is required for affinity. About affinity no longer detailed here, you can query the document.


All the activity in a task works as a whole. The entire task (the entire activity stack) can be pushed to the foreground or pushed to the background. Suppose that there are three activity under a running task in which four activity--are running, when the user presses the home key, returns to the program launcher and runs the new application (actually running a new task), Then the current task is back in the background, and the root activity of the newly opened application is displayed, and after a while the user returns to the application and then selects the previous application (the prior task), the previous task is back at the front. , when the user presses the back key, the screen does not show the activity of the newly opened application that has just left, but is the activity at the top of the task stack, which is returned to the foreground, to show the next activity of the task. These are activities and task-general behavior, but almost all aspects of this behavior can be modified. The relationship between activity and task, and the behavior of activities in a task, is influenced by the identity of the intent object that initiates the action and the attributes of the <Activity> element in the manifest file.


The above is a description of the activity and task.

In the development of Android projects, users will inevitably do program switching, in the process, the program will go into the background to run, need to use the Task Manager or click the program or by clicking the icon in the message to return to the original interface. This effect is similar to the effect of Tencent QQ, open QQ after showing the main interface, in the use of other programs, QQ will be in the form of icons displayed in the Information Notice bar, if the use of QQ and then click on the Information Notice bar icon display QQ main interface.

Let's take a look at this example to implement the effect chart:

In the second figure in the figure above, we will return to the original activity when we click.

When our program goes backstage, it appears as an icon in the top of our emulator, as shown in the following figure:

The general practice for this effect is to write the appropriate code in the OnStop () method in the activity, because the OnStop () method is invoked when the activity enters the background, and we can OnStop () Method displays the program icon and information in notification form, where the code looks like this:

@Override
 protected void OnStop () {
 //TODO auto-generated method Stub
 super.onstop ();
 LOG.V ("BACKGROUND", "program into the Background");
 Shownotification ();
 }

The above Shownotification () method is notification.

Then click on the notification of the information notification bar and return to the original activity.

Of course, we can also capture the home key, which displays notification when the user presses the home key, and here's the code example:

 Click the Home button to run the program into
 the background @Override public
 boolean onKeyDown (int keycode, keyevent event) {
  //TODO auto-generated method Stub
  //press Home key
  if (keycode = = keyevent.keycode_home) {
   //Show Notification
   notification = new Notificationextend (this);
   Notification.shownotification ();
   Movetasktoback (true);    
 
   return true;
  }
  
  Return Super.onkeydown (KeyCode, event);
 }

The notificationextend here is an encapsulation of the display notification, and the code in the class is as follows:

Package com.test.background;
Import android.app.Activity;
Import android.app.Notification;
Import Android.app.NotificationManager;
Import android.app.PendingIntent;
Import android.content.Intent;

Import Android.graphics.Color; /** * Notification Extended class * @Description: Notification Extension class * @File: Notificationextend.java * @Package Com.test.backgroun D * @Author Hanyonglu * @Date 2012-4-13 pm 02:00:44 * @Version V1.0 * * public class Notificationextend {private Ac
 
 Tivity context;
 Public Notificationextend {//TODO auto-generated constructor stub this.context = context; }//Show notification public void Shownotification () {//Create a Notificationmanager reference Notificationmanager Notificatio
  
  Nmanager = (Notificationmanager) context.getsystemservice (Android.content.Context.NOTIFICATION_SERVICE); Defines the various properties of Notification Notification Notification = new Notification (R.drawable.icon, "reader", System.currenttimem
  Illis ()); Place this notice on the notification bar "ONgoing "is running" group Notification.flags |= notification.flag_ongoing_event;
  Indicates that this notification is automatically cleared after clicking "Purge Notification" in the notification bar.
  Notification.flags |= notification.flag_auto_cancel notification.flags |= notification.flag_show_lights;
  Notification.defaults = notification.default_lights;
  Notification.ledargb = Color.Blue;
    
  NOTIFICATION.LEDONMS = 5000; Set the event message for the notification charsequence contenttitle = "Reader display information"; Notification Bar title Charsequence ContentText = "Push message display, see ...";
  Notification bar content Intent notificationintent = new Intent (Context,context.getclass ());
  Notificationintent.setaction (Intent.action_main);
  Notificationintent.addcategory (Intent.category_launcher); Pendingintent contentintent = pendingintent.getactivity (context, 0, Notificationintent,pendingintent.flag_update_
  Current);
  Notification.setlatesteventinfo (context, Contenttitle, ContentText, contentintent);
 Pass the notification to Notificationmanager notificationmanager.notify (0, notification); //Cancel notification public void Cancelnotification (){Notificationmanager Notificationmanager = (notificationmanager) context.getsystemservice (Android.content.C Ontext.
  Notification_service);
 Notificationmanager.cancel (0);

 }
}

There is a need to set up each activity in the configuration file to run on a single task, otherwise each return to the original will add a new one, not return to the original.

A phenomenon that does not return to the original activity occurs when the Flag_activity_new_task is used to control the identity. If the identity causes an activity to start a new task, then when the user presses the home key to leave the activity, the user can no longer return to the original activity when he presses the back key. Some applications (such as notification) always open the activity in a new task and never open it in their own task, so they will always contain flag_activity_new_ The intent of the task is passed to StartActivity (). So if there is an activity that can be invoked by something else with this control flag, be aware that the application has an independent method of returning to the original activity. The code is as follows:

 <activity android:name= "showmessageactivity"
    android:launchmode= "Singletask" ></activity> 

Here's what you need to be aware of:

The Launchmode property under <activity> can be set up with four startup modes:

    • Standard (default mode)
    • Singletop
    • Singletask
    • SingleInstance

These four modes have several different points:

1. Which task the activity will be loaded in response to intent.

For the standard and Singletop modes, the activity--of the task that generated the intent (Invoke StartActivity ()) is held by the other, unless the intent object contains Flag_activity_new_task flags. Then you'll look for a new task.

Conversely, the singtask and singleinstance patterns, which always flag an activity as the root of a task, open such activities to create a new task instead of loading a running task.

2. Whether an activity can have multiple instances.

An activity of a standard or singletop attribute can be instantiated multiple times, they can belong to several different tasks, and a task can contain multiple instances of the same activity.


Conversely, an activity of the Singletask or SingleInstance attribute can have only one instance (a single example), because the activity is at the bottom of the task, which means that the task can have only one instance at the same time of the same device.

3. Whether an instance can allow other activity in its task.

An activity of a singleinstance property is the only activity in its task, and if he initiates another activity, the activity is loaded into a different task and ignores its startup mode- It's like a Flag_activity_new_task logo in intent. In other respects, singleinstance and Singletask are the same.

Three other modes allow multiple activity in a task, an activity of a singletask attribute is always a root activity in a task, But he can start another activity and load the new activity into the same task, and the activity of the standard and Singletop attributes can appear anywhere in the task.

4. Whether to create a new instance of the activity to handle a new intent.

For the default standard method, new instances will be generated to handle each new intent. Each instance handles a new intent.

For Singletop mode, if an existing instance is on the top of the target task, reuse the instance to handle the new intent, if the instance exists but is not on the top of the stack, it is not reused. Instead, recreate an instance to process the new intent and press the instance onto the stack.


For example, now there is a task stack abcd,a is the root activity,d is the top activity, now there is a startup D of the intent, if D is the default standard method, then a new instance will be created to handle this intent, So the stack becomes ABCDD, but if D is the Singletop way, the D of the already existing stack will handle the intent, so the stack is ABCD.

In the other case, the arrival of the intent is given to B, regardless of whether B is standard or singletop (because now B is not on the top of the stack), a new instance is created, so the stack becomes abcdb.


As mentioned above, an activity in a "singletask" or "singleinstance" mode will only have one instance, so that their instance will handle all the new intent. A "singleinstance" activity is always on top of the stack.

(because it is the only activity in a task), it can always handle a intent. and a "singletask" activity on the stack can have or no other activity on it. If so, it cannot process the new intent, intent will be discarded. (Even if intent is discarded, its arrival will bring the task to the front desk and remain there.) )

When an existing activity is requested to process a new intent, the intent object is passed through the onnewintent () call to the event. (The original intent object passed in can be obtained by calling Getintent ().)


Note that when you create an instance of a new activity to handle a newly received intent, the user can press the back key to return to the previous state (the previous activity). However, when using an existing activity instance to manipulate the newly received intent, the user cannot return to the status of the instance before receiving the new intent by pressing the back key.

Oh, sorry, pull a little bit more, we continue to look at our program.

Here, if you can do this for an activity implementation, if there are multiple events, we need to rewrite the onkeydown event in each of these and catch the user pressing the home key.

In order to achieve convenience, we can use a service dedicated to monitor whether the program into the background or foreground work, if the program into the background to run the display notification, so no matter how many activities in the program can be very convenient to implement the program before and after the switch.

To do this, I have added a new Appstatusservice class to the program to monitor whether the program is running in the background, or to display an informational prompt if running in the background.

The code is as follows:

Package com.test.service;

Import java.util.List;
Import com.test.background.MainActivity;
Import Com.test.background.NotificationExtend;
Import COM.TEST.BACKGROUND.R;

Import Com.test.util.AppManager;
Import Android.app.ActivityManager;
Import android.app.Notification;
Import Android.app.NotificationManager;
Import android.app.PendingIntent;
Import Android.app.ActivityManager.RunningAppProcessInfo;
Import Android.app.Service;
Import Android.content.Context;
Import android.content.Intent;
Import Android.graphics.Color;
Import Android.os.IBinder;

Import Android.util.Log; /** * Monitor Whether the service is running in the front background * @Description: Whether the listener runs in the front background service * @FileName: Appstatusservice.java * @Package com.tes T.service * @Author Hanyonglu * @Date 2012-4-13 pm 04:13:47 * @Version V1.0 * * public class Appstatusservice Extend 
 s service{private static final String TAG = "Appstatusservice"; 
 Private Activitymanager Activitymanager;
 Private String PackageName;
 
 Private Boolean isstop = false; @Override Public IBinder OnbIND (Intent Intent) {//TODO auto-generated method stub return null;
  @Override public int Onstartcommand (Intent Intent, int flags, int startid) {//TODO auto-generated method stub 
  Activitymanager = (Activitymanager) this.getsystemservice (Context.activity_service); 
  PackageName = This.getpackagename ();
  
  System.out.println ("Start Service"); 
      
      New Thread () {public void run () {The try {while (!isstop) {thread.sleep (1000);
      if (Isapponforeground ()) {LOG.V (TAG, "foreground run");
       else {log.v (TAG, "run in the background");
      Shownotification (); 
    A catch (Exception e) {e.printstacktrace ()); 
  
  }}.start ();
 Return Super.onstartcommand (Intent, flags, Startid); /** * Program is running in the foreground * @return * * public boolean Isapponforeground () {//Returns a list of application Processe s that are running on the device list<runningappprocessinfo> appprocesses = Activitymanager.getrunningappprocesseS (); 
  
  if (appprocesses = null) return false; for (Runningappprocessinfo appprocess:appprocesses) {//The name of the process, that, this object, associated with 
   . if (AppProcess.processName.equals (packagename) && appprocess.importance = = Runningappprocessinfo.importance 
   _foreground) {return true; 
 return false;
  @Override public void OnDestroy () {//TODO auto-generated Method Stub Super.ondestroy ();
  SYSTEM.OUT.PRINTLN ("Termination of Service");
 Isstop = true; }//Show notification public void Shownotification () {//Create a Notificationmanager reference Notificationmanager Notificatio
  
  Nmanager = (Notificationmanager) getsystemservice (Android.content.Context.NOTIFICATION_SERVICE); Defines the various properties of Notification Notification Notification = new Notification (R.drawable.icon, "reader", System.currenttimem
  Illis ());
  Place this notice in the "ongoing", the "Running" group, in the notification bar notification.flags |= notification.flag_ongoing_event; Automatically clear notification after clicking
  Notification.flags |= Notification.flag_auto_cancel;
  Notification.flags |= notification.flag_show_lights;
  Notification.defaults = notification.default_lights;
  Notification.ledargb = Color.Blue;
    
  NOTIFICATION.LEDONMS = 5000; Set the event message for the notification charsequence contenttitle = "Reader display information"; Notification Bar title Charsequence ContentText = "Push message display, see ...";
  Notification bar content Intent notificationintent = new Intent (Appmanager.context,appmanager.context.getclass ());
  Notificationintent.setaction (Intent.action_main);
  Notificationintent.addcategory (Intent.category_launcher); Pendingintent contentintent = pendingintent.getactivity (appmanager.context, 0, Notificationintent,
  Pendingintent.flag_update_current);
  Notification.setlatesteventinfo (Appmanager.context, Contenttitle, ContentText, contentintent);
 Pass the notification to Notificationmanager notificationmanager.notify (0, notification);

 }
}

In order to return to the original activity after clicking in the Message Bar, we need to write down our current activity in the AppManager.

PS: Does the listener enter the background
Method One:

/**
  * To determine whether the current application is in the foreground or background
  * * @param context * @return/public
 Static Boolean Isapplicationbroughttobackground (Final context) {
  Activitymanager am = (activitymanager) Context.getsystemservice (context.activity_service);
  list<runningtaskinfo> tasks = am.getrunningtasks (1);
  if (!tasks.isempty ()) {
   ComponentName topactivity = tasks.get (0). topactivity;
   if (!topactivity.getpackagename (). Equals (Context.getpackagename ()) {return
    true;
   }
  }
  return false;
 
 }

This code requires a permission:

<uses-permission android:name= "Android.permission.GET_TASKS"/>

Method Two:

/**
* * 
@param context
* @return
/public static Boolean IsBackground (context context) {
 
 
Activitymanager Activitymanager = (activitymanager) context
. Getsystemservice (context.activity_service);
list<runningappprocessinfo> appprocesses = Activitymanager
. getrunningappprocesses ();
for (Runningappprocessinfo appprocess:appprocesses) {
if (appProcess.processName.equals) ( Context.getpackagename ())) {
if (appprocess.importance = = runningappprocessinfo.importance_background) {
LOG.I (String.Format ("Background App:", Appprocess.processname));
return true;
} else{
log.i (String.Format ("Foreground App:", Appprocess.processname));
return false;
}} return false;
}

Method Three:
Provided by using the API

@Override
 protected void Onuserleavehint () {//When the user presses the home key, and so on to start the program into the background when the timer
  super.onuserleavehint ();
  if (!isleave) {
   isleave=true;
   Savestarttime ();
  }
 

This needs to be added with a intent flag
public static final int flag_activity_no_user_action
or call startactivity from one activity in turn, Finish closes itself, and when you start a new activity, Onuserleavehint is also called

Related Article

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.