android不同activity之间共享数据解决方法
时间:2023-12-22 04:30:45
最近做局域网socket连接问题,要在多个activity之间公用一个socket连接,就在网上搜了下资料,感觉还是application方法好用,帖出来分享下!
Android中在不同Activity中传递变量,通常使用Intent中Bundle添加变量的操作方法。
保存参数时:
Intent intent = new Intent();
intent.setClass(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("name", "xiaozhu");
intent.putExtras(bundle);
startActivity(intent);
读取参数:
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");
不过在多个Activity中经常使用同一变量时,使用Bundle则比较麻烦,每次调用Activity都需要设置一次。
如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Application context。
新建一个类,继承自Application
class MyApp extends Application {
private String myState;
public String getState() {
return myState;
}
public void setState(String s) {
myState = s;
}
}
在AndroidManifest.xml的application加个name属性就可以了,如下面所示:
<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">
使用时:
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
标签:android,activity
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring boot如何快速的配置多个Redis数据源
2023-05-12 18:27:32
Java实现单例模式的五种方法介绍
2022-10-20 17:32:56
浅述int与string类型转换的两种方法
2023-09-09 08:56:28
SpringCloud分布式链路跟踪的方法
2023-11-24 23:42:19
![](https://img.aspxhome.com/file/2023/6/59936_0s.png)
Java实现部门员工管理
2021-07-21 21:40:41
![](https://img.aspxhome.com/file/2023/4/81944_0s.jpg)
深入理解C#中new、override、virtual关键字的区别
2021-08-29 05:42:37
解决MyEclipse中的Building workspace问题的三个方法
2023-10-25 09:00:51
![](https://img.aspxhome.com/file/2023/2/81252_0s.png)
Java常用流程控制语句实现原理解析
2023-11-08 14:11:34
spring boot集成smart-doc自动生成接口文档详解
2023-11-28 23:08:02
![](https://img.aspxhome.com/file/2023/3/60773_0s.png)
Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup
2023-02-19 23:22:37
![](https://img.aspxhome.com/file/2023/1/78851_0s.jpg)
JAVA使用动态代理对象进行敏感字过滤代码实例
2021-07-29 13:27:26
Java中ArrayList与顺序表的定义与实现方法
2022-06-08 03:27:12
![](https://img.aspxhome.com/file/2023/7/67197_0s.png)
java打印菱形及直角和等腰三角形的方法
2023-01-08 20:46:55
![](https://img.aspxhome.com/file/2023/6/88756_0s.png)
Android Handler,Message,MessageQueue,Loper源码解析详解
2022-04-17 17:34:57
![](https://img.aspxhome.com/file/2023/7/103867_0s.png)
浅谈Java获得多线程的返回结果方式(3种)
2023-04-02 05:37:36
解决Android SDK下载和更新失败的方法详解
2021-07-04 21:28:57
![](https://img.aspxhome.com/file/2023/0/139260_0s.jpg)
C#实现23种常见的设计模式的示例详解
2022-10-19 20:28:29
Java实现俄罗斯方块的源码分享
2023-02-17 04:20:48
![](https://img.aspxhome.com/file/2023/2/69902_0s.png)
js判断是否含有GBK以外的字符的函数
2022-01-25 16:47:52
Android动画之逐帧动画(Frame Animation)实例详解
2023-02-27 06:12:56