Data sharing solution between android and different activity

  • 2020-05-07 20:23:41
  • OfStack

Recently do LAN socket connection problem, to be in a number of activity public 1 socket connection, on the Internet to search the information, feel or application method is good, post out to share!
Android passes variables in different Activity, usually using Bundle in Intent to add variables.
When saving parameters:
 
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:
 
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 frequently used in multiple Activity, Bundle is more troublesome, and Activity needs to be set once for each call.
If you want to use it throughout the application, java 1 USES static variables, while android has a more elegant way of using Application context.
Create a new class inherited from Application
 
class MyApp extends Application { 
private String myState; 
public String getState() { 
return myState; 
} 
public void setState(String s) { 
myState = s; 
} 
} 

Just add an name attribute to application of AndroidManifest.xml, as shown below:
 
<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name"> 

When using:
 
class Blah extends Activity { 
@Override 
public void onCreate(Bundle b){ 
... 
MyApp appState = ((MyApp)getApplicationContext()); 
String state = appState.getState(); 
... 
} 
} 

Related articles: