安卓开发手记 之 intent 传递数据的另外几种方式
来源:互联网 发布:vb pdfview.ocx使用 编辑:程序博客网 时间:2024/05/29 14:34
这里有一篇关于intent 的基本使用http://blog.csdn.net/mr_miaomiao/article/details/9762013 ;
当然除了这些基本的使用之外,还有其他经常使用的 传递数据的方式 ;
一,使用静态变量传递数据
1,新建一个android 工程,我们做一个简单demo,在原有 mianActivity 的基础上添加一个 OtherActivity ,然后在 mainActivity.xml 添加一个button
<Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="98dp" android:text="Button" />
新建 布局文件 other.xml 添加一个 textview<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.20" /> </LinearLayout>
2,在 otherActivity .java onCreate() 里添加如下代码 ,public class OtherActivity extends Activity{public static String name;private TextView tx;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.other);tx = (TextView) this.findViewById(R.id.textView1);//name="mr_miaomiao";tx.setText("name :"+name);}}
3, 在mainActivity.java oncreate 里添加如下代码public class MainActivity extends Activity {private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//跳转到下一个activityIntent intent = new Intent();intent.setClass(MainActivity.this, OtherActivity.class);//修改其静态变量的值OtherActivity.name="@夏苗苗长见识了";startActivity(intent);}}); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
4.,最后我们来改下清单文件 androidManifest.xml<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.xiamiaomiao.testintent001" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.xiamiaomiao.testintent001.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=".OtherActivity"></activity> </application></manifest>
部署在模拟器上试试。小结:其实使用静态变量传数据 就是在activity 里声明一个静态变量在 系统为它初始化前 赋值 。
二,android 中Application
有过javaee 开发经验的童鞋们都知道 有个 jsp 内置对象 application ,它的生命周期和 服务器 一起,应用启动时创建服务器挂了 ,就没了,在android 里也有个极其相似的 东西 android.application
下面我们来看看它的使用方式:
为了方便我们接着上面的例子,新建一个java类--------MyApp 继承自 Application ,我们需要重写onCreate()方法,该方法表示该对象的创建,我们可以在这个方法里初始化我们需要的数据。
package com.xiamiaomiao.application;import android.app.Application;public class MyApp extends Application {private String name;private String weibo;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getWeibo() {return weibo;}public void setWeibo(String weibo) {this.weibo = weibo;}@Overridepublic void onCreate() {super.onCreate();this.name ="mr_miaomiao";this.weibo = "@夏苗苗长见识了";}}
1,,我们修改一下mainActivity 的代码,来从MyApp 里获取数据展示到 other 的 textview 里 。(ps:真是不错的想法。。。。)public class MainActivity extends Activity {private MyApp myapp;private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//跳转到下一个activityIntent intent = new Intent();intent.setClass(MainActivity.this, OtherActivity.class);myapp = (MyApp) getApplication();intent.putExtra("name", myapp.getName());intent.putExtra("weibo", myapp.getWeibo());//修改其静态变量的值//OtherActivity.name="@夏苗苗长见识了";startActivity(intent);}}); }
2.,修改 otherActivity .java 中的代码protected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.other);tx = (TextView) this.findViewById(R.id.textView1);Intent intent = getIntent();String name =intent.getStringExtra("name");String weibo = intent.getStringExtra("weibo");tx.setText("name :"+name +"\n"+"weibo : "+weibo);}
只是从 intent 里取了一些数据 ,3,其实这些已经差不多了,但是还有一个地方不要忘记了,那就是你的清单文件 ,对application 节点 修改如下
<application android:name="com.xiamiaomiao.testintent001" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.xiamiaomiao.application.MyApp"
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>
运行一下试试看。
小结:myapp 对象 在任何一个activity 里 都可以被调用,可以存储一些app 的全局变量;
三,android 中的剪切板
事实上在android 里使用剪切板来传递数据 也是一种不错的选择,特别是我们要传递一些自定义对象的时候 ;下面我们来看看
如何使用;
1,现在我们新建一个android application ---------TestClipboard (不知道拼错没有。。。)
和上面一样新建一个 otherActiviy.java ,顺带也建好 布局文件 ,在里面加入一个 textview ,
2,下面我们在 mainActivity 里 启动剪切板服务 在里面储存 我们要放的数据
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() {@SuppressLint("NewApi") @Overridepublic void onClick(View arg0) {//启动剪切板服务ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);ClipData cd= ClipData.newPlainText("name", "xiamiaomiao");cm.setPrimaryClip(cd);Intent intent = new Intent();intent.setClass(MainActivity.this, NewActivity.class);startActivity(intent);}}); }3,接下来看看如何在otherActivity 里获取这个 内容
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.new_activity);tx = (TextView) this.findViewById(R.id.textView1);ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);if(cm.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ClipData cd = cm.getPrimaryClip();Item it = cd.getItemAt(0);System.out.println(cd.getItemCount());tx.setText(it.getText());}}
4,配置好你的清单文件后试试看 ,是不是同样可以获取到数据
5,,紧接着 我们试试用剪切板来传递一个复杂的对象,新建一个java 类 emp .java
package com.xiamiaomiao.model;import java.io.Serializable;public class Emp implements Serializable{/** * */private static final long serialVersionUID = 1L;private int id;private String name;private String dept;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDept() {return dept;}public void setDept(String dept) {this.dept = dept;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Emp(int id, String name, String dept, int age) {super();this.id = id;this.name = name;this.dept = dept;this.age = age;}@Overridepublic String toString() {return "Emp [id=" + id + ", name=" + name + ", dept=" + dept + ", age="+ age + "]";}}
6,修改mainActivity 中部分代码如下protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() {@SuppressLint("NewApi") @Overridepublic void onClick(View arg0) {ObjectOutputStream oos = null;ByteArrayOutputStream bos = null;ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);String empStr ="";ArrayList<Emp> emps = new ArrayList<Emp>();emps.add(new Emp(1, "001", "a", 20));emps.add(new Emp(2, "002", "b", 20));emps.add(new Emp(3, "003", "c", 20));emps.add(new Emp(4, "004", "d", 20));try {bos = new ByteArrayOutputStream();oos = new ObjectOutputStream(bos);oos.writeObject(emps);//转码成字符串 empStr = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);System.out.println(empStr);} catch (IOException e) {e.printStackTrace();}finally{try {bos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {oos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}ClipData cd= ClipData.newPlainText("emps",empStr);cm.setPrimaryClip(cd);Intent intent = new Intent();intent.setClass(MainActivity.this, NewActivity.class);startActivity(intent);}}); }
7,修改OtherActivity 中代码 如下,(同样都是传递的字符串,只不过这里传递一个对象时,需要序列化)protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.new_activity);tx = (TextView) this.findViewById(R.id.textView1);ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);if(cm.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){ClipData cd = cm.getPrimaryClip();Item it = cd.getItemAt(0);byte[] buf = Base64.decode(it.getText().toString(), Base64.DEFAULT);ByteArrayInputStream bis = new ByteArrayInputStream(buf);ObjectInputStream ois = null;try {ois = new ObjectInputStream(bis);ArrayList<Emp> emps = (ArrayList<Emp>) ois.readObject();tx.setText(emps.toString());} catch (StreamCorruptedException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}finally{try {bis.close();} catch (IOException e) {e.printStackTrace();}try {ois.close();} catch (IOException e) {e.printStackTrace();}}}}
小结:使用剪切板传递复杂对象时 ,需要借助 base64 自带工具,进行压缩,解压缩,用到了java 对象流;
- 安卓开发手记 之 intent 传递数据的另外几种方式
- 安卓通过putExtra传递数据的几种方式
- Intent传递对象的几种方式
- Intent传递对象的几种方式
- Android之Intent传递数据的方式
- 安卓-Intent传递数据
- Android开发之Intent数据的传递
- 安卓开发手记 intent 返回结果
- 【Android 开发】 : Activity之间传递数据的几种方式
- 【Android 开发】 : Activity之间传递数据的几种方式
- iOS开发:传递数据的几种方式
- 【Android 开发】 : Activity之间传递数据的几种方式
- Intent传递数据的方式
- android 开发手记 activity 之间数据的传递 intent 对象的使用
- android 关于intent传递类对象的几种方式
- 安卓开发——Intent能传递的数据类型
- 安卓开发之 Intent的介绍
- Android 数据传递的几种方式
- 下拉框高度具体数值
- Android的EditText设置默认值和设置提示的方法
- floor函数
- Error: MySQL server is requesting the old and insecure pre-4.1 auth mechanism.
- 通过手机音频口,实现与单片机通讯,做电子签名成功
- 安卓开发手记 之 intent 传递数据的另外几种方式
- What is the difference between test, [ and [[ ?
- 数据库查询
- 关于Html无宽度居中
- 单例设计模式(懒汉式和饿汉式区别)
- 学习Python(十)
- Linux网络设置1——Linux网络环境配置
- ubuntu12.04下配置LAMP
- Android设置页面没有标题的方法