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+"");先写到这里。
晚安。
浙公网安备 33010602011771号