Android shared data resolution between different activity _android

Source: Internet
Author: User
Recently do LAN socket connection problem, to be in a common socket connection between the activity, on the Internet search under the information, feeling or application method easy to use, post out to share!
In Android, you pass variables in different activity, usually using the bundle method of adding variables in intent.
When saving parameters:
Copy Code code as follows:

Intent Intent = new Intent ();
Intent.setclass (A.this, B.class);
Bundle Bundle = new Bundle ();
Bundle.putstring ("name", "Xiaozhu");
Intent.putextras (bundle);
StartActivity (Intent);

Read parameters:
Copy Code code as follows:

Intent Intent = This.getintent ();
Bundle Bundle = Intent.getextras ();
String name = bundle.getstring ("name");
[Java] View plaincopy
Intent Intent = This.getintent ();
Bundle Bundle = Intent.getextras ();
String name = bundle.getstring ("name");

However, when using the same variable frequently in multiple activity, using bundle is cumbersome, and each call to the activity needs to be set once.
For use throughout the application, static variables are generally used in Java, and a more elegant approach to Android is to use the application context.
Create a new class that inherits from application
Copy Code code as follows:

Class MyApp extends Application {
Private String MyState;
Public String getState () {
return mystate;
}
public void SetState (String s) {
MyState = s;
}
}

You can add a name attribute to the Androidmanifest.xml application, as shown in the following:
Copy Code code as follows:

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

When used:
Copy Code code as follows:

Class Blah extends Activity {
@Override
public void OnCreate (Bundle b) {
...
MYAPP appstate = ((MyApp) Getapplicationcontext ());
String state = Appstate.getstate ();
...
}
}
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.