簡體   English   中英

如何通過 Intent 將對象發送到 Android 中的另一個 Activity?

[英]How to send the object via intent to another Activity in Android?

我正在Android中開發。 我嘗試將藍牙對象發送到另一個活動。

代碼

    BluetoothSocket btSocket;

Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra(EXTRA_BT_SOCKET,btSocket);
startActivity(i);

但它似乎不起作用,並顯示如下錯誤:

無法解析方法 'putExtra(java.lang.String, android.bluetooth.BluetoothSocket)

如何通過意圖將藍牙對象發送到 Android 中的另一個活動?

提前致謝。

您不能將BluetoothSocket實例放入Bundle或將其作為Intent “extra” 那樣傳遞。 這將需要序列化和反序列化對象,這將創建對象的副本。 你不能像那樣復制一個套接字。 您想要做的只是在多個活動之間共享對象。 最簡單的方法是將對象的引用放在某個地方的public static變量中,然后從所有需要訪問的活動中使用它。

使用以下命令發送和檢索對象:

//傳遞:intent.putExtra("MyClass", obj);

// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");

使用輔助類

public class BluetoothSocketHelper implements Serializable {

    public BluetoothSocket btSocket;

    //Constructor + getter/setters
}

從 ActivityA 發送:

BluetoothSocketHelper bluetoothSocketHelper;

Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra(DeviceListActivity.EXTRA_ADDRESS, address);
i.putExtra(EXTRA_BT_SOCKET, bluetoothSocketHelper);
startActivity(i);

然后在活動B中:

private BluetoothSocket btSocket;

if(getIntent().getExtras()!=null){
    bluetoothSocketHelper = (BluetoothSocketHelper) getIntent().getSerializableExtra(EXTRA_BT_SOCKET);
    btSocket = (BluetoothSocket) bluetoothSocketHelper.getBluetoothSocket();
}

嘿@Wun 我知道為時已晚,但我找到了一種簡單的方法來做到這一點,在您的第一個活動中,只需啟動活動並發送您的對象:

Intent intent = new Intent(this, Second.class);
intent.putExtra("rideId", yourObject);
startActivity(intent);

在第二個活動中:

String id = extras.getString("rideId");
try {
   JSONObject mJsonObject = new JSONObject(id);
} catch (JSONException e) {
   e.printStackTrace();
}

你可以通過意圖將它作為一個包傳遞

 Bundle bundle = new Bundle();
 bundle.putParcelable("yourObject key name", YOUR_OBJECT); //make YOUR_OBJECT implement parcelable
 Intent intents = new Intent(ActivityA.this, ActivityB.class);
 intents.putExtra(Constants.BUNDLE_DATA, bundle);
 startActivity(intents);

在接收端(ActivityB.class)

if (intent != null && intent.hasExtra(Constants.BUNDLE_DATA)) {
        Bundle bundle = intent.getBundleExtra(Constants.BUNDLE_DATA);
        if (bundle != null && bundle.containsKey(yourObject key name)) {
            Object yourObject = bundle.getParcelable(yourObject keyname);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM