English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

تفصيل طريقة نقل المعلمات المعقدة بين intents في Android

本文详细讲述了Android intent之间复杂参数传递方法。分享给大家供大家参考,具体如下:

Intent是Activity与Activity之间,Activity与Service之间传递参数的介质,而这两种通常实现的是Java基本对象类型和String的传递。
在实际项目中,页面之间传值,除了以上几种,经常还有传递Object对象、List类型、List<Object>类型和全局变量等等的需求。本文就是介绍怎么传递这几种类型的参数。

一、传递List<String>和List<Integer>

以下以传递List<String>为例,发送List<String>语法为:

intent.putStringArrayListExtra(key, list);

接收List<String>的语法为:

list = (ArrayList<String>)getIntent().getStringArrayListExtra(key);

以下是一个运用实例:

// =============发送List<String>=============
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("string1");
stringList.add("string2");
stringList.add("string3");
Intent intent = new Intent();
intent.setClass(ListDemoActivity.this, StringListActivity.class);
intent.putStringArrayListExtra("ListString", stringList);
startActivity(intent);
// ====================接收List<String>======================
ArrayList<String> stringList = (ArrayList<String>) getIntent().getStringArrayListExtra("ListString");

List<Integer>类似的操作调用下面的方法也可以实现发送和接收:

intent.putIntegerArrayListExtra(key, list);
list =(ArrayList<Integer>) getIntent().getIntegerArrayListExtra(key);

二、使用Serializable和Parcelable两种方式传递Object

Android的Intent之间传递对象有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是Bundle.putParcelable(Key,Object)。方法中的Object要满足一定的条件,前者实现了Serializable接口,而后者实现了Parcelable接口。

以下是实现了Serializable接口的User类,命名为SerializableUser纯粹是从类名方便区分实现了Parcelable接口的User类,实际开发中不建议这么命名:

public class SerializableUser implements Serializable {
  private String userName;
  private String password;
  public SerializableUser() {
  }
  public SerializableUser(String userName, String password) {
    this.userName = userName;
    this.password = password;
  }
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
}

以下是实现了Parcelable接口的User类:

public class ParcelableUser implements Parcelable {
  private String userName;
  private String password;
  public ParcelableUser() {
  }
  public ParcelableUser(String userName, String password) {
    this.userName = userName;
    this.password = password;
  }
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
  public static final Parcelable.Creator<ParcelableUser> CREATOR = new Creator<ParcelableUser>() {
    @Override
    public ParcelableUser createFromParcel(Parcel source) {
      ParcelableUser parcelableUser = new ParcelableUser();
      parcelableUser.userName = source.readString();
      parcelableUser.password = source.readString();
      return parcelableUser;
    }
    @Override
    public ParcelableUser[] newArray(int size) {
      return new ParcelableUser[size];
    }
  };
  @Override
  public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
  }
  @Override
  public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub
    dest.writeString(userName);
    dest.writeString(password);
  }
}

باستخدام طريقتيننقلالجملة المختلفة هي:

bundle.putSerializable(key,object);
bundle.putParcelable(key,object);

باستخدام طريقتينإستقبالالجملة المختلفة هي:

object=(Object) getIntent().getSerializableExtra(key);
object=(Object) getIntent().getParcelableExtra(key);
// ============= استعمالSerializable و Parcelable لارسال الهدف ==============
SerializableUser serializableUser = new SerializableUser("user1", "123456");
ParcelableUser parcelableUser = new ParcelableUser("user2","654321");
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("serializableUser", serializableUser);
bundle.putParcelable("parcelableUser", parcelableUser);
intent.setClass(ListDemoActivity.this, ObjectActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// ============= استقبال Object ==============
SerializableUser serializableUser = (SerializableUser) getIntent().getSerializableExtra("serializableUser");
ParcelableUser parcelableUser = (ParcelableUser) getIntent().getParcelableExtra("parcelableUser");

ربما لاحظ البعض أن تحقيق Serializable واجهة تعني تسلسل العنصر ثم النقل، لا يوجد فرق واضح في البرمجة العادية لـ Java، وUser لا يتطلب تغييرًا واضحًا، وهو بسيط. وأوصي بهذه الطريقة أيضًا.

ومع ذلك، تحقيق Parcelable واجهة الفئات يُعد معقدًا نوعًا ما، Parcelable ما هو؟

يقدم Android نوعًا جديدًا: Parcel، الذي يُستخدم كحاوية لتغليف البيانات، وتُغلف البيانات بعد ذلك يمكن نقلها عبر Intent أو IPC. بالإضافة إلى الأنواع الأساسية، يمكن وضع فقط الفئات التي تحقق Parcelable واجهة داخل Parcel.

لتحقيق Parcelable واجهة يجب تحقيق ثلاث طرق:

1) writeToParcel الطريقة. هذه الطريقة تكتب بيانات الفئة إلى Parcel المقدم من الخارج.
البيان: writeToParcel (Parcel dest, int flags).

2) describeContents الطريقة. يمكن أن تعود بـ 0 مباشرة.

3) الثابت Parcelable.Creator<T> واجهة، هذه الواجهة تحتوي على طريقتين:

createFromParcel(Parcel in) implements the function of creating an instance of the class from in.
newArray(int size) creates an array of type T with a length of size, return new T[size]; can be. This method is for external classes to deserialize the array of this class.

The running status of the program can be tested by log output. When calling the public void writeToParcel(Parcel dest, int flags) method of ParcelableUser class at the time of bundle.putParcelable("parcelableUser", parcelableUser);, data is written to dest. When ParcelableUser parcelableUser = (ParcelableUser) getIntent().getParcelableExtra("parcelableUser");, the public ParcelableUser createFromParcel(Parcel source) method of ParcelableUser class is called to create a ParcelableUser object and assign values to the properties of this object. Here, Parcel source and Parcel dest are the same, and then the ParcelableUser object is returned. Finally, you can print out the attribute information of parcelableUser.

III. Passing List<Object>

What should we do if we need to pass a List of Objects, that is, List<Object>? First, we need to implement the Serializable interface for the Object object, then force the type conversion of the list to Serializable type, and finally pass through:

Intent.putExtra(key, (Serializable) objectList);

This syntax is used to pass. The receiver also needs to perform a forced type conversion to List<Object> when receiving, and the syntax used to receive List<Object> is:

objectList = (List<Object>) getIntent().getSerializableExtra(key);

The following is an application example. The SerializableUser class used here was provided in the previous step, so it will not be repeated here.

// ==============Send List<Object>===========
SerializableUser user1 = new SerializableUser("user1", "123456");
SerializableUser user2 = new SerializableUser("user2", "654321");
List<SerializableUser> objectList = new ArrayList<SerializableUser>();
objectList.add(user1);
objectList.add(user2);
Intent intent = new Intent();
intent.setClass(ListDemoActivity.this, ObjectListActivity.class);
intent.putExtra("ListObject", (Serializable) objectList);
startActivity(intent);
// ====================استقبال List<Object>======================
List<SerializableUser> objectList = (List<SerializableUser>) getIntent().getSerializableExtra("ListObject");

الجزء الرابع: المتغيرات العالمية

إذا كانت هناك معلمات مستوى التطبيق خاصة غير مريحة استخدامها عبر intent لتحويل المعلمات، يسهل التفكير في إمكانية استخدام المتغيرات العالمية أو المتغيرات الصلبة (static variables). المتغيرات الصلبة في Java تعتبر مناسبة هنا، لكن قيمتها تفقد بعد تنفيذ Activity System.exit(0) أو finish().

في Android، هناك طريقة أكثر جمالًا هي استخدام ApplicationContext. هذه الطريقة في التعامل مع المتغيرات العالمية أكثر أمانًا من استخدامهذه الكلاسات الصلبة (static classes)، حيث يتم إطلاقها فقط بعد أن يتم تدمير جميع Activities التطبيق.

يوجد في SDK الخاص بـ Android ذكر أن التطبيق (Application) مخصص لتخزين المتغيرات العالمية، ويكون موجودًا عند إنشاء حزمة (package). لذا، عند الحاجة إلى إنشاء متغيرات عالمية، لا يتطلب الأمر مثلما في J2SE إنشاء متغيرات statice من نوع public، بل يمكن تحقيق ذلك مباشرة داخل التطبيق. كل ما يتطلب هو الت 호출 getApplicationContext من سياق (Context) أو التطبيق getApplication من Activity للحصول على كائن Application لتحديد أو قراءة قيمة المتغيرات العالمية.

启动Application时,系统会创建一个PID,即进程ID,所有的Activity就会在此进程上运行。那么我们在Application创建的时候初始化全局变量,同一个应用的所有Activity都可以取到这些全局变量的值,换句话说,我们在某一个Activity中改变了这些全局变量的值,那么在同一个应用的其他Activity中值就会改变。

用法:

1. 创建一个属于你自己的android.app.Application的子类,为想要共享的private全局变量增加setter和getter方法。

public class MyApp extends Application{
  private String globalVariable;
  public String getGlobalVariable() {
    return globalVariable;
  }
  public void setGlobalVariable(String globalVariable) {
    this.globalVariable = globalVariable;
  }
}

2. 在manifest中申明一下这个类,这时Android就为此建立一个全局可用的实例。

其实就是在原来仅有的一个application标签上为application制定一个名字为这个全局实例。

<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">

3. 可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。

// ============使用全局变量传递参数==============
MyApp myApp = ((MyApp) getApplicationContext()); //获得我们的应用程序MyApp
myApp.setGlobalVariable("عالمية");
Intent intent = new Intent();
intent.setClass(ListDemoActivity.this, GlobalActivity.class);
startActivity(intent);
// ============ استقبال متغيرات العناصر العالمية =============
MyApp myApp = ((MyApp) getApplicationContext());
String globalVariable = myApp.getGlobalVariable();

للمزيد من المعلومات المتعلقة بـ Android يمكن للقراء المهتمين الاستمتاع بالمقالات الخاصة بالموقع: 'دليل البدء والتحسين في تطوير Android'، 'تقديم تقنيات التشغيل للنشاطية activity في Android'، 'تجميع تقنيات التعامل مع الموارد في Android'، 'تجميع تقنيات التعامل مع الملفات في Android'، 'تجميع تقنيات التعامل مع قاعدة البيانات SQLite في Android'، 'تجميع تقنيات التعامل مع البيانات بتنسيق json في Android'، 'تجميع تقنيات التعامل مع قاعدة البيانات في Android'، 'تجميع تقنيات التعامل مع SD card في تطوير Android'، 'تجميع تقنيات عرض الرؤى View في Android'، وتجميع تقنيات استخدام التحكمات في Android'.

آمل أن يساعدك محتوى هذا المقال في تصميم برامج Android.

البيان: محتويات هذا المقال تم جمعها من الإنترنت، ويتمتع المالك الأصلي بحقوق الطبع والنشر، ويتم جمع المحتوى من قبل المستخدمين عبر الإنترنت وعرضه بشكل مستقل، ويتمتع هذا الموقع بحقوق الملكية، ولا يتم تعديل المحتوى بشكل إنساني، ولا يتحمل الموقع أي مسؤولية قانونية تتعلق بذلك. إذا كنت قد وجدت محتوى يشتبه في انتهاك حقوق النسخ، فيرجى إرسال بريد إلكتروني إلى: notice#oldtoolbag.com (عند إرسال البريد الإلكتروني، يرجى استبدال '#' بـ '@') لتقديم الشكوى، وتقديم الأدلة ذات الصلة، وإذا تم التحقق من صحة الشكوى، فإن هذا الموقع سيزيل المحتوى المشبوه فوراً.

أعجبك ذلك