Android设置全局变量&&启动系统自带应用程序
Android设置全局变量&&启动系统自带应用程序
一.开发过程中有时不可避免的要使用全局变量.
之前的做法都是直接按照java的方式设置静态变量public static int 来定义一个全局变量,后来发现这个值有时就莫名其妙的消失了.估计是随activity生命周期或者Android回收机制给搞没了.找到答案了.
另一个适合android的全局变量方法:
1.建一个全局类
- 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();
- ...
- }
- }
- <application android:name=".MyApp"
- android:icon="@drawable/icon"
- android:label="@string/app_name">
二.通过包名启动程序.
我们知道要调用一个程序,要知道一个程序的包名和Activity名.比如调用短信时
- Uri smsUri = Uri.parse("tel:10086");
- returnIt = new Intent(Intent.ACTION_VIEW, smsUri);
- returnIt.putExtra("sms_body", "yyyy");
- returnIt.setType("vnd.android-dir/mms-sms");
但是有时要启动一些山寨手机自带的系统软件时.你不知道Activity名.就可以直接用包名启动系统自带的程序.
- Intent intent = getPackageManager().getLaunchIntentForPackage("com.android.xxxxxxx");
- if(intent!=null)startActivity(intent);
评论暂时关闭