Android 通过Application 传递数据
2017-07-05 16:45 tlnshuju 阅读(177) 评论(0) 收藏 举报</pre><pre>
package com.example.ApplicationTest;
import android.app.Application;
/**
 * Created by chang on 14-10-1.
 */
public class App extends Application {
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String name;
    @Override
    public void onCreate() {
        super.onCreate();
        setName("张三");
    }
}
package com.example.ApplicationTest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MyActivity extends Activity {
    private Button btnLaunch = null;
    private App myApp;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnLaunch = (Button)this.findViewById(R.id.btnLaunch);
        myApp = (App)this.getApplication();
        myApp.setName("hello");
        btnLaunch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyActivity.this,OtherActivity.class);
                startActivity(intent);
            }
        });
    }
}
package com.example.ApplicationTest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
/**
 * Created by chang on 14-10-1.
 */
public class OtherActivity extends Activity {
    private App myApp;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);
        textView = (TextView)findViewById(R.id.showMsg);
        myApp = (App)getApplication();
        textView.setText(myApp.getName());
    }
}
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.ApplicationTest" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="19"/> <application android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:name=".App"> <activity android:name="MyActivity" 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=".OtherActivity" > </activity> </application> </manifest>
 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号