博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于Android 中的Context
阅读量:4172 次
发布时间:2019-05-26

本文共 1909 字,大约阅读时间需要 6 分钟。

The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.
--如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Application context。
As you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.
--每个Activity 都是Context,其包含了其运行时的一些状态,android保证了其是single instance的。
The way to do this is to create your own subclass of android.app.Application,and then specify that class in the application tag in your manifest.Now Android will automatically create an instance of that class andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):
--方法是创建一个属于你自己的android.app.Application的子类,然后在manifest中申明一下这个类,这是android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。
给个例子:
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
复制代码
This has essentially the same effect as using a static variable orsingleton, but integrates quite well into the existing Androidframework. Note that this will not work across processes (should yourapp be one of the rare ones that has multiple processes).
--这个效果就是使用静态变量是一样的,但是其更符合android的架构体系。

转载地址:http://eebai.baihongyu.com/

你可能感兴趣的文章
巧用二进制,让性能提升100倍,让存储空间减少100倍
查看>>
Java单例模式实现,一次性学完整,面试加分项
查看>>
大型分布式网站架构总结
查看>>
死磕18个Java8日期处理,工作必用!收藏起来~
查看>>
【建议收藏】Spring Boot注解全梳理!
查看>>
卧槽!牛皮了,头一次见有大佬把TCP三次握手四次挥手解释的这么明白
查看>>
面试 Redis 没底?这 40 道面试题让你不再慌(附答案)
查看>>
浅谈Java Web经典三层架构和MVC框架模式
查看>>
MySQL 常用优化指南,及大表优化思路都在这了!
查看>>
JVM原理与深度调优
查看>>
在线等,Kafka如果丢了消息怎么办?
查看>>
如何设计实现一个通用的微服务架构?高可靠、高可用思维模型
查看>>
20张图助你了解JVM运行时数据区,你还觉得枯燥吗?
查看>>
MQ消息中间件,面试能问写什么?
查看>>
为什么Zookeeper天生就是一副分布式锁的胚子?
查看>>
Java面试问题之 volatile 关键字到底是什么?
查看>>
读书单
查看>>
一张图看懂JVM之垃圾回收算法详解
查看>>
阿里社招面试如何准备?谈谈对于Java程序猿学习中各个阶段的建议,文末有福利
查看>>
阿里架构师:程序员必须掌握的几项技术能力
查看>>