Define global variables in android. app. Application

Source: Internet
Author: User

To use global variables in Android apps, in addition to static variables of public, you can also use android. app. Application in a more elegant way.

When the Application is started, the system creates a PID, that is, the process ID, and all the activities will run on this process. In this case,
When the global variables are initialized, all the activities of the same application can obtain the values of these global variables.

For example, save the logon status in Application
AndroidMenifest. xml

<application
android:name=".CombankDroid"
android:icon="@drawable/first_aid"
android:label="@string/app_name" >
</application>

CombankDroid. java

public class CombankDroid extends Application {
private boolean isLogin;

public boolean isLogin(){
return isLogin
}
public void setIsLogin(boolean b){
isLogin = b;
}
}

Anyhow. java

class Anyhow extends Activity {

@Override
public void onCreate(Bundle b){
...

CombankDroid combankDroid = ((CombankDroid)getApplicationContext());
//CombankDroid combankDroid = (CombankDroid) getApplication();

// Don't start the main activity if we don't have credentials
if (!combankDroid.isLogin()) {
redirectToLoginActivity();
} else {
loadUi();
}

...
}

...
}
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.