Solve the problem of NULL pointers for Android apps being killed or applied for recycling

Source: Internet
Author: User

1. How did the problem occur and under what circumstances would such problems occur?

This null pointer problem can occur when the user uses the Phone cleanup Assistant or the background to recycle our app, causing our application process to be killed, let's take a look at how this happens.

we create a new program demo, the program has three activity, respectively, Splashactivity mainactivity Infoactivity, hereinafter referred to as the three activity for a B C. These three activities also simulate the entry process for our usual project, splashactivity is our welcome page, and we let it finish when the activity is displayed. Mainactivity is our main page, usually this page startup mode is set to Singletask, do not understand why this mode is set to the students can go to Baidu activity startup mode, and Infoactivity is our level two page.

As we customize a application class, we all know that this class is first loaded at the start of the program, and we define a collection list in this.
See here we may be puzzled, why to define such a collection??
A: This set is intended to facilitate our simulation of NULL pointer anomalies, of course, this is only a convenient simulation, we can be in the daily development of other reasons for such problems.
Next we look at the initialization of this set. you can see that this set is new when initialized in Mainactivity, and we assign a value to it.

 Public  class mainactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); myapplication.list=NewArraylist<> (); MyApplication.list.add ("I came from mainactivity.");        Button button= (button) Findviewbyid (R.ID.ACTIVITY_MAIN_BTN); Button.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {StartActivity (NewIntent (mainactivity. This, Infoactivity.class));    }        }); }}

When we click on the button and jump to the infoactivity, let's see how the infoactivity is handled.

publicclass InfoActivity extends AppCompatActivity {    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_info);        TextView textView= (TextView) findViewById(R.id.text);        textView.setText(MyApplication.list.get(0));    }}

It's easy to just assign a control to a value.

OK, let's look at the whole process.

haha, very simple!! Next, let's simulate the occurrence of anomalies! We put the app on the Infoactivity page while pressing the home button to put the program in the background, then use Android studio to force the end of our process, then click on the app and we'll see what happens.

We'll find out when we open the app again! Hey! An exception has occurred!!

Let's analyze why this happens, obviously because the collection is empty when assigning a value to TextView, and our collection is new and assigned in Mainactivity. While our process is being strongly killed or recycled, the Android system does not let your process, but the information in the activity stack in this process is still there, In other words, when you open this application, the activity stack in the program still exists b→c the two activity, but the data in the activity is not, need to re-create new activity data, that is, to re-walk the life cycle, When our infoactivity goes back to 14, because the data in the mainactivity is not initialized (only if we fall back to mainactivity to walk the life cycle), and this collection is initialized in Mainactivity, So this set is definitely empty. This also results in the occurrence of NULL pointer exceptions.

2. Problem solving
In fact, the idea is very simple, since our process has been recycled, and then open the application will be forced to go directly to the START process can be, that is, let our application re-a→b→c this process can be!
The first step: we need to create a new singleton class, Android, the Singleton class is linked to our entire application life cycle, that is, when the application process has not been the case of the Singleton class is not, and the Singleton class will not be collected by GC, so do not worry about the problem of being recycled, as follows:

/** * Created by Lvzishen on 2016/5/5. * * App Status Tracker constant code */ Public  class appstatusconstant {     Public Static Final intstatus_force_killed=-1;//Application was put in the background by the strong kill     Public Static Final intstatus_kick_out=1;//token fail or be kicked off the downline     Public Static Final intStatus_normal=2;//app is normal//public static final int status_logout=2;//user logoff login//public static final int status_offline=3;//not logged in status//public static final int status_online=4;//login status    //intent to mainactivity to distinguish the purpose of jumping     Public Static FinalString key_home_action="Key_home_action";//Return to Main page     Public Static Final intAction_back_to_home=6;//Default value     Public Static Final intaction_restart_app=9;//Be forced to kill     Public Static Final intaction_kick_out=Ten;//Be kicked out}
 Public classAppstatusmanager { Public intAppstatus= appstatusconstant.status_force_killed;//app Status Initial value is not started in foreground state     Public StaticAppstatusmanager Appstatusmanager;Private Appstatusmanager() {    } Public StaticAppstatusmanagergetinstance() {if(Appstatusmanager = =NULL) {Appstatusmanager =NewAppstatusmanager (); }returnAppstatusmanager; } Public int Getappstatus() {returnAppstatus; } Public void Setappstatus(intAppstatus) { This. appstatus = Appstatus; }}

As shown above, we have created a new app state constant class to facilitate uniform parameters, and a new Appstatus Singleton class, which defines an int type parameter with the default value of-1, which is the default status of the process shutdown, and when is this value changed? It is easy to change the OnCreate method in Spalshactivity. Change to normal 2 in spalshactivity.

 Public  class splashactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {appstatusmanager.getinstance (). Setappstatus (Appstatusconstant.status_normal);//Enter app initialization set to not logged in state        Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_splash); Handler.sendemptymessagedelayed (0, the); } Handler Handler =NewHandler () {@Override         Public void Handlemessage(Message msg) {Super. Handlemessage (msg); StartActivity (NewIntent (splashactivity. This, Mainactivity.class));        Finish (); }    };}

When we stay on a page when the application is recycled unified jump to mainactivity can, because mainactivity is singletask boot mode, so at this time the activity stack is only left mainactivity an activity, In the mainactivity finish off their own at the same time in the jump splashactivity can be completed, so that the app is forced to go back to the START process, in order to unified management, we create a new baseactivity, Other activty inherit this baseactivity, and the modified code is as follows:

/** * Created by Lvzishen on 2016/5/5. * * Public Abstract  class baseactivity extends appcompatactivity {    /** * @param savedinstancestate * *    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);Switch(Appstatusmanager.getinstance (). Getappstatus ()) {/** * Application is strongly killed */             CaseAppstatusconstant.status_force_killed://Jump to home page, home Lauchmode singletaskProtectapp (); Break;/** * User was kicked or token expired */             CaseAppstatusconstant.status_kick_out://Popup dialog, click to jump to homepage, clear user information, run exit login logic//Intent intent=new Intent (this,mainactivity.class);//StartActivity (intent);                 Break; CaseAppStatusConstant.STATUS_NORMAL:setUpContentView ();                Setupview (); SetupData (savedinstancestate); Break; }    }/** * Loading layouts * /    protected Abstract void Setupcontentview();/** * View initialization * /    protected Abstract void Setupview();/** * Load data * /    protected Abstract void SetupData(Bundle savedinstancestate);protected void Protectapp() {Intent Intent =NewIntent ( This, Mainactivity.class);        Intent.putextra (Appstatusconstant.key_home_action, Appstatusconstant.action_restart_app);    StartActivity (Intent); }@Override     Public void onbackpressed() {//returns to the default end of the current pageFinish (); }}
 Public  class splashactivity extends baseactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {appstatusmanager.getinstance (). Setappstatus (Appstatusconstant.status_normal);//Enter app initialization set to not logged in state        Super. OnCreate (Savedinstancestate); }@Override    protected void Setupcontentview() {Setcontentview (R.layout.activity_splash); }@Override    protected void Setupview() {    }@Override    protected void SetupData(Bundle savedinstancestate) {handler.sendemptymessagedelayed (0, the); } Handler Handler =NewHandler () {@Override         Public void Handlemessage(Message msg) {Super. Handlemessage (msg); StartActivity (NewIntent (splashactivity. This, Mainactivity.class));        Finish (); }    };}
 Public  class mainactivity extends baseactivity {Button button;@Override    protected void Setupcontentview() {Setcontentview (r.layout.activity_main); }@Override    protected void Setupview() {button= (button) Findviewbyid (R.ID.ACTIVITY_MAIN_BTN); }@Override    protected void SetupData(Bundle savedinstancestate) {myapplication.list=NewArraylist<> (); MyApplication.list.add ("I came from mainactivity."); Button.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {StartActivity (NewIntent (mainactivity. This, Infoactivity.class));    }        }); }@Override    protected void Protectapp() {Toast.maketext (Getapplicationcontext (),"Application is recycled to restart the process.", Toast.length_long). Show (); StartActivity (NewIntent ( This, Splashactivity.class));    Finish (); }@Override    protected void onnewintent(Intent Intent) {Super. Onnewintent (Intent);intAction = Intent.getintextra (appstatusconstant.key_home_action, appstatusconstant.action_back_to_home);Switch(action) { CaseAPPSTATUSCONSTANT.ACTION_RESTART_APP:PROTECTAPP (); Break; CaseAppstatusconstant.action_kick_out: Break; CaseAppstatusconstant.action_back_to_home: Break; }    }}
 Public  class infoactivity extends baseactivity {TextView TextView;@Override    protected void Setupcontentview() {Setcontentview (r.layout.activity_info); }@Override    protected void Setupview() {TextView textview= (TextView) Findviewbyid (R.id.text); }@Override    protected void SetupData(Bundle savedinstancestate) {Textview.settext (MyApplication.list.get (0)); }}

As shown in the code above, we change the state to normal in Spalshactivity, while the app state is judged in baseactivity, as long as the process is recycled appstatusmanager is recreated, int Status because there is no walk splashactivity, so it is the default value-1, in the Baseactivity OnCreate method to determine the int status will walk Protectapp () This method (normal will not go), Rewrite this method in mainactivity to jump to spalshactivity and finish the whole process! We use this idea can also deal with such issues as single sign-on downline! Let's look at the effect after the makeover.

We stuck the page in mainactivity while forcing the process to close, you can see the re-opened the application process, while the toast appears, indicating that the application is to go mainactivity Protectapp method. All right, just talk about here, say the wrong place please mention, thank you for reading!!

Solve the problem of NULL pointers for Android apps being killed or applied for recycling

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.