当前位置: 代码迷 >> Android >> android application类简介(1)
  详细解决方案

android application类简介(1)

热度:34   发布时间:2016-04-28 05:35:19.0
android application类简介(一)

每次应用程序运行时,应用程序的application类保持实例化的状态。通过扩展applicaiton类,可以完成以下3项工作:

1.对android运行时广播的应用程序级事件如低低内做出响应。

2.在应用程序组件之间传递对象(全局变量)。

3.管理和维护多个应用程序组件使用的资源。

其中,后两项工作通过使用单例类来完成会更好。application会在创建应用程序进程的时候实例化。

下面是扩展Application的示例代码:

import android.app.Application;public class MyApplication extends Application {	private static MyApplication singleton;	//返回应用程序实例	public static MyApplication getInstance(){		return singleton;	}	@Override	public void onCreate() {		super.onCreate();		singleton = this;	}}
 在创建好自己的Application后,在mainfest里面的application注册,如下:

<application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:name="com.example.i18n.MyApplication"        android:theme="@style/AppTheme" >

至于get 和set :

假如MyApplication有变量str,并提供getter和setter,如下:

package com.example.i18n;import android.app.Application;public class MyApplication extends Application {	private static MyApplication singleton;	private String str;	//返回应用程序实例	public static MyApplication getInstance(){		return singleton;	}	@Override	public void onCreate() {		super.onCreate();		singleton = this;	}	public String getStr() {		return str;	}	public void setStr(String str) {		this.str = str;	}	}

使用str和赋值:

	MyApplication.getInstance().setStr("hello,bitch!");		String mystr = MyApplication.getInstance().getStr();		Log.e("str",mystr+"");


先写到这里。晚安。

  相关解决方案