ภาพรวม
ตัวอย่างนี้สาธิตวิธีดึงและแสดง Package Name ของแอปพลิเคชัน Android ปัจจุบัน โดยใช้เมธอด getPackageName() ของ Context
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
// ดึงและแสดง Package Name
textView.setText("Package Name: " + getPackageName());
}
}
การทดสอบ
รันแอป จะแสดง Package Name เช่น "com.example.myapplication"
การใช้งาน Package Name ในทางปฏิบัติ
1. เปิด Settings ของแอปตัวเอง
Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
2. เช็คว่าแอปอื่นติดตั้งอยู่หรือไม่
public boolean isAppInstalled(String packageName) {
try {
getPackageManager().getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
3. แชร์แอปผ่าน Play Store
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Check out this app: https://play.google.com/store/apps/details?id=" + getPackageName());
startActivity(Intent.createChooser(shareIntent, "Share via"));
4. ใช้เป็น Key ใน SharedPreferences
SharedPreferences prefs = getSharedPreferences(getPackageName() + "_prefs", MODE_PRIVATE);
ข้อมูล Package อื่นๆ ที่มีประโยชน์
// Version Name String versionName = BuildConfig.VERSION_NAME; // Version Code int versionCode = BuildConfig.VERSION_CODE; // Application ID (จาก build.gradle) String applicationId = BuildConfig.APPLICATION_ID;