android 使用Intent传递数据之全局变量传递
16lz
2021-01-23
android中的全局对象非常类似于javaWeb中的Application域,除非是android应用程序清楚内存,否则全局对象将一直可以访问。
android中有一个application类,是基类。创建自己的应用的时候需要继承这个基类,并实现onCreate方法,该方法在application被调用的时候就会启动。
创建自己的application类:
package com.example.intent;import android.app.Application;public class MyApp extends Application {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}/** * @param args */@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();this.name="mayi";this.age=23;}}
创建了自己的app后,必须在AndroidManifest.xml中定义自己的应用,
<application android:name=".MyApp" //定义自己的app android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity 在其他activity中调用app: package com.example.intent;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.widget.TextView;public class OtherActivity extends Activity {private MyApp myapp;private TextView textview;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.other);textview = (TextView)this.findViewById(R.id.msg);myapp = (MyApp)getApplication(); //获得APPtextview.setText("name: "+myapp.getName()+"\n"+"age: "+myapp.getAge());}}
更多相关文章
- Android中定义样式(1)
- Android 多线程之synchronized锁住的是代码还是对象(二)
- Android Handler机制5之Message简介与消息对象对象池
- Android 设置完autoLink属性后自定义跳转到指定界面
- Android注解:自定义注解之源码注解
- Android 自定义字体
- Android自定义样式style.xml
- Android 替换全局字体
- 自定义对话框Dialog