Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีอ่าน SharedPreferences ของแอปอื่นใน Android

ภาพรวม

ตัวอย่างนี้แสดงวิธีการเข้าถึง SharedPreferences ของแอปพลิเคชันอื่น โดยใช้ createPackageContext และโหมด MODE_WORLD_READABLE (API ล้าสมัย) หรือ Content Provider (แนะนำ)

⚠️ ข้อควรระวัง: การเปลี่ยนแปลงของ Android

  • API 17+ (Android 4.2+): MODE_WORLD_READABLE และ MODE_WORLD_WRITEABLE ถูก Deprecated เพื่อความปลอดภัย
  • แนวทางที่แนะนำ: ใช้ Content Provider หรือ FileProvider เพื่อแชร์ข้อมูลระหว่างแอป
  • ตัวอย่างนี้แสดงโค้ดเก่าเพื่อการศึกษาเท่านั้น ไม่ควรใช้ใน Production

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress" />
    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="text" />
    <Button
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Save"
        android:text="Save" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Clear"
        android:text="Clear Data" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Retrieve"
        android:text="Retrieve Data" />
</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java) - แอปต้นทาง

package com.example.sharedprefdemo;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    EditText etName, etEmail;
    SharedPreferences sharedPreferences;
    public static final String MY_PREF = "myPref";
    public static final String NAME_KEY = "nameKey";
    public static final String EMAIL_KEY = "emailKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        etName = findViewById(R.id.etName);
        etEmail = findViewById(R.id.etEmail);
        sharedPreferences = getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
        
        loadData();
    }

    private void loadData() {
        if (sharedPreferences.contains(NAME_KEY)) {
            etName.setText(sharedPreferences.getString(NAME_KEY, ""));
        }
        if (sharedPreferences.contains(EMAIL_KEY)) {
            etEmail.setText(sharedPreferences.getString(EMAIL_KEY, ""));
        }
    }

    public void Clear(View view) {
        etName.setText("");
        etEmail.setText("");
        Toast.makeText(this, "Cleared", Toast.LENGTH_LONG).show();
    }

    public void Retrieve(View view) {
        loadData();
        Toast.makeText(this, "Retrieved", Toast.LENGTH_LONG).show();
    }

    public void Save(View view) {
        String name = etName.getText().toString();
        String email = etEmail.getText().toString();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(NAME_KEY, name);
        editor.putString(EMAIL_KEY, email);
        editor.apply();
        Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
    }
}

วิธีเข้าถึงจากแอปอื่น (Deprecated - สำหรับการศึกษา)

// ในแอปอื่นที่ต้องการอ่านข้อมูล
try {
    Context otherAppContext = createPackageContext("com.example.sharedprefdemo", Context.CONTEXT_IGNORE_SECURITY);
    SharedPreferences sharedPref = otherAppContext.getSharedPreferences("myPref", Context.MODE_PRIVATE);
    
    String name = sharedPref.getString("nameKey", "");
    String email = sharedPref.getString("emailKey", "");
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

แนวทางที่แนะนำ: ใช้ Content Provider

สร้าง Content Provider ในแอปต้นทาง แล้วแอปอื่นๆ สามารถ Query ข้อมูลได้อย่างปลอดภัย

ขั้นตอนที่ 4: ตั้งค่า Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.sharedprefdemo">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

การทดสอบ

รันแอปพลิเคชันบนอุปกรณ์จริง ทดสอบบันทึก ล้าง และดึงข้อมูล SharedPreferences

วิธีอ่าน SharedPreferences ของแอปอื่นใน Android วิธีอ่าน SharedPreferences ของแอปอื่นใน Android