I recently had a local area network socket connection problem. To share a socket connection between multiple activities, I searched the internet for information. I still feel that the application method is easy to use. I will post it and share it with you!
In Android, variables are transmitted in different activities. Generally, you can use the Bundle in Intent to add variables.
When saving parameters:
Copy codeThe Code is 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 codeThe Code is 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 the same variable is often used in multiple activities, it is troublesome to use Bundle. You need to set it once each time you call the Activity.
To use it in the entire Application, static variables are generally used in java, while the more elegant method in android is Application context.
Create a new class that inherits from the ApplicationCopy codeThe Code is as follows: class MyApp extends Application {
Private String myState;
Public String getState (){
Return myState;
}
Public void setState (String s ){
MyState = s;
}
}
Add the name attribute to the AndroidManifest. xml application, as shown below:Copy codeThe Code is as follows: <application android: name = ". MyApp" android: icon = "@ drawable/icon" android: label = "@ string/app_name">
Use Time:Copy codeThe Code is as follows: class Blah extends Activity {
@ Override
Public void onCreate (Bundle B ){
...
MyApp appState = (MyApp) getApplicationContext ());
String state = appState. getState ();
...
}
}