如何在Android中與其他應用程式共享應用程式資料?
在 Android 中,使用隱式意圖,我們可以使用 ACTION_SEND 動作將資料傳送到其他應用程式。我們需要呼叫 Intent.createChooser() 來開啟 Android 手機的預設選擇器以傳送資料。它在不同的 Android 手機上可能相同或不同。
此示例演示如何在 Android 中與其他應用程式共享應用程式資料。
步驟 1 - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟 2 - 將以下程式碼新增到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:id="@+id/layout" android:gravity="center" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/data" android:layout_width="match_parent" android:gravity="center" android:textSize="30sp" android:text="www.tutorialspoint.com" android:layout_height="wrap_content" /> </LinearLayout>
在上面的程式碼中,它包含一個 TextView,當用戶點選 TextView 時,它將使用其他應用程式傳送 TextView 的資料。
步驟 3 - 將以下程式碼新增到 src/MainActivity.java 中
package com.example.andy.myapplication; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public int counter; @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView textView = findViewById(R.id.data); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(); i.setAction(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_TEXT, textView.getText().toString()); startActivity(Intent.createChooser(i, "Share to")); } }); } }
上面的程式碼包含一個 TextView,當您點選 TextView 時,它將使用意圖傳送資料。
步驟 4 - 無需更改 manifest.xml 檔案
讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 手機裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您的專案中的一個 Activity 檔案,然後點選工具欄中的執行圖示 。選擇您的手機裝置作為選項,然後檢查您的手機裝置,它將顯示您的預設螢幕 -
這是您首次點選 tutorialspoint.com 時的初始螢幕,它將從您的 Android 裝置開啟預設選擇器,如下所示 -
選擇任何應用程式以透過該應用程式傳送資料。我們可以將資料傳送給一個人或將資料釋出到您的牆上,這取決於選擇器應用程式。
點選 此處 下載專案程式碼
廣告