การเปิดแอปพลิเคชันอื่นด้วย Package Name
ใน Android สามารถเปิดแอปพลิเคชันอื่นได้โดยใช้ Package Name ผ่าน Intent
ขั้นตอนการทำงาน
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
ไปที่ File → New Project ใน Android Studio
ขั้นตอนที่ 2: เพิ่มเลย์เอาต์ใน res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:background="#33FFFF00"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:textSize="18sp"
android:text="Click to open YouTube"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
ขั้นตอนที่ 3: เพิ่มโค้ด Java ใน src/MainActivity.java
package com.example.andy.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout parent = findViewById(R.id.parent);
textView = findViewById(R.id.text);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent launchIntent = getPackageManager()
.getLaunchIntentForPackage("com.google.android.youtube");
if (launchIntent != null) {
startActivity(launchIntent);
} else {
Toast.makeText(MainActivity.this,
"ไม่พบแอปพลิเคชัน YouTube ในอุปกรณ์",
Toast.LENGTH_LONG).show();
}
}
});
}
}
โค้ดสำคัญ:
Intent launchIntent = getPackageManager()
.getLaunchIntentForPackage("com.google.android.youtube");
if (launchIntent != null) {
startActivity(launchIntent);
} else {
Toast.makeText(this, "ไม่พบแพ็กเกจ", Toast.LENGTH_LONG).show();
}
การทดสอบ
รันแอปพลิเคชัน คลิกข้อความ "Click to open YouTube" จะเปิดแอป YouTube (หากติดตั้งอยู่) หรือแสดง Toast แจ้งเตือนหากไม่มี