如何在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:id="@+id/parent" xmlns:tools="http://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>
在上面的程式碼中,我們建立了一個 TextView。單擊 TextView 時,它將開啟 YouTube。
步驟 3 − 將以下程式碼新增到 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 {
int view = R.layout.activity_main;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
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, "There is no package available in android", Toast.LENGTH_LONG).show();
}
}
});
}
}在上面的程式碼中,我們使用了 YouTube 的包名來開啟 YouTube 應用程式,如下所示:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.youtube");
if (launchIntent != null) {
startActivity(launchIntent);
} else {
Toast.makeText(MainActivity.this, "There is no package available in android", Toast.LENGTH_LONG).show();
}讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您的一個專案活動檔案,然後單擊工具欄中的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:

在上面的結果中,它顯示了預設螢幕,當您單擊 TextView 時,它將開啟 YouTube,如下所示:

點選此處下載專案程式碼
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP