单利模式的懒汉模式,在Android的源码中应用的还是相当普遍的。在android的开发中,有时候需要一个Context的变量,同时还需要使用单例模式,那么该怎么处理呢?
- 在getInstance的时候,进行传递context变量。这样的方式,在android源码中还是很普遍的。
/**
* 单例模式的懒汉模式
* 传递了一个上下文参数 context ,如此就能够实现新建一个线程,能有ui的操作
* 参考:http://blog.csdn.net/l2show/article/details/46672061 和 android 源码
*/
public class DownloadInfo {
private static final String TAG = "DownloadInfo";
private Context mContext;
private static DownloadInfo mDownloadInfo;
private Handler mToastHandler;
private static final int DOWNLOADNOTHING = 0;
private DownloadInfo(Context context) {
this.mContext = context;
new Thread(){
public void run(){
Looper.prepare();
mToastHandler = new Handler(Looper.myLooper()){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case DOWNLOADNOTHING:
Toast.makeText(mContext,"DOWNLOADNOTHING",Toast.LENGTH_SHORT).show();
}
}
};
Looper.loop();
}
}.start();
}
public static DownloadInfo getInstance(Context context){
if(mDownloadInfo ==null){
mDownloadInfo = new DownloadInfo(context);
}
return mDownloadInfo;
}
public void showNothingToast(){
if(mToastHandler != null){
mToastHandler.sendEmptyMessage(DOWNLOADNOTHING);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
public class MainActivity extends AppCompatActivity {
private DownloadInfo downloadInfo;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
downloadInfo = DownloadInfo.getInstance(context);
downloadInfo.showNothingToast();
}
}
以上代码能实现在一个单例的线程中更新ui界面的功能。