Context and global variable analysis in Android

Source: Internet
Author: User

When studying context today, I have a certain understanding of application and activity context. The following documents are copied from the Internet,

Differences between application context and activity context:

These are two different contexts and the most common ones. In the first type, the life cycle of context is related to the life cycle of application. context is destroyed with the destruction of application, and the life cycle of application is irrelevant to the life cycle of activity. Context in the second type is related to the lifecycle of the activity. However, for an application, the activity can be destroyed several times, and the context of the activity will be destroyed multiple times. For which context is used, it depends on the Application Scenario. I personally feel that the context of the activity is better, but sometimes the context of the application must be used. Application context can be obtained through context. getapplicationcontext or activity. getapplication.

Also, when using context, be careful with Memory leakage to prevent memory leakage. Pay attention to the following aspects:

1. Do not make an object with a long life cycle reference the activity context. That is, make sure that the object that references the activity has the same life cycle as the activity itself.

2. For objects with a long life cycle, you can use application context

3. Avoid non-static internal classes and try to use static classes to avoid lifecycle issues. Pay attention to the lifecycle changes caused by internal class references to external objects.

Now let's go back to the topic and talk about the global variables of Android. During normal development, some global data may be required to make all the activities and views in the application accessible, when you encounter this situation, you may first think of defining a class and then creating many static members. Android has provided us with a solution to this situation:
In Android, there is an application class. In activity, you can use the getapplication () method to obtain the instance, and use it to obtain the topic of the current application and content in the resource file, A more flexible feature of this class is that it can be inherited to add its own global attributes. For example, to develop a game and save scores, We can inherit the application. Below is a demo using the code http://www.eoeandroid.com/thread-30257-1-1.html#. in practice, the modified content is correct.

First, write a subclass of the application:

import android.app.Application;public class GameApplication extends Application {    private int score;    public int getScore() {        return score;    }    public void setScore(int score) {        this.score = score;    }}

Modify the following in the manifest. xml file:

<application android:name=".GameApplication" android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".DemoActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name="ResultActivity"></activity>    </application>

You have added Android: Name = ". gameapplication ".

After the modification, let's look at it again:

public class DemoActivity extends Activity {    public Button button;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);             button=(Button)findViewById(R.id.button);        ((GameApplication)getApplication()).setScore(100);        button.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {Intent intent=new Intent();intent.setClass(DemoActivity.this, ResultActivity.class);startActivity(intent);}});    }}

Scores are set in this activity, which can be obtained from other activities:

Public class resultactivity extends activity {@ override protected void oncreate (bundle savedinstancestate) {// todo auto-generated method stub super. oncreate (savedinstancestate); setcontentview (R. layout. other); textview TV = (textview) findviewbyid (R. id. TV); int score = (gameapplication) getapplicationcontext ()). getscore (); TV. settext ("your score is:" + score );}}

This is just a simple example. Of course, if you want to complete the above functions, you can use intent to pass values, which is still troublesome. However, if there are many activities, using this method will find very useful. Is it possible to use sharepreference to accomplish similar functions? Yes, but the efficiency is much worse than this. sharepreference is mainly used to store data, you can save the simple data to be saved to the sharepreference when you exit the program. Of course, sqllite must be used for complex data.



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.