application和sharedpreference的区别

来源:互联网 发布:mysql 递归查询 编辑:程序博客网 时间:2024/06/04 00:21

在android程序中,我们经常用intent来传递数据,但是intent传递的数据类型太少了。因此我们经常通过以下两种方法来传递数据。

一.sharedpreference(用法网上有,这里不再说明)

二.application
Application对象的生命周期是整个程序中最长的,它的生命周期就等于这个程序的生命周期。因为它是全局的单例的,所以在不同的Activity,Service中获得的对象都是同一个对象。所以可以通过Application来进行一些,如:数据传递、数据共享和数据缓存等操作。

用法
(1)编写一个类继承Application
功能很简单,就是“设置,获取,加一”三个功能

public class MyApp extends Application {    private int number;    @Override    public void onCreate() {        super.onCreate();    }    public void set(int number){        this.number = number;    }    public void increase(){        number++;    }    public int get(){        return number;    }}

(2)定义第一个activity
设置全局变量,然后转到下一个activity

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        MyApp myApp = (MyApp) getApplicationContext();        myApp.set(5);        Log.i(this.getClass().getName(), myApp.get() + "");        startActivity(new Intent(this, SecondActivity.class));        finish();    }}

(3)定义第二个activity
把全局变量加一然后显示

public class SecondActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main2);        MyApp myApp = (MyApp) getApplicationContext();        myApp.increase();        Log.i(this.getClass().getName(), myApp.get() + "");    }}

(4)AndroidManifest.xml配置(很重要)

<application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme"        android:name=".MyApp" > //////////////////////**看这里*/        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name="SecondActivity"></activity>    </application>

demo的效果
这里写图片描述

个人推荐使用application。因为第一sharedpreference传递的数据类型有限。而且无法避免多线程访问冲突;第二如果使用真机调试的话sharedpreference文件不好查看

0 0
原创粉丝点击