Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 匿名啟動 Activity 與啟動系統 Activity

編輯:關於 Android 程式設計

平常我們用 Intent 進行 Activity 跳轉時,通常都知道目標 Activity 的類別。但當目標不在同一個 App 內,甚至想跳到系統自帶的功能時,就得靠「匿名啟動」這套 Action 機制了。

基本跳轉

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);

匿名啟動

首先在被啟動的 SecondActivity 的 AndroidManifest.xml 中配置 intent-filter,加上 action 與 category:

<intent-filter>
    <action android:name="toSecondPage" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

FirstActivity 便能透過 action 名稱找到它:

Intent intent = new Intent();
intent.setAction("toSecondPage");
startActivity(intent);

如此一來,即使目標 Activity 不屬於本 App,也能透過 ActionName 成功跳轉。

啟動系統 Activity

原理相同,只要使用系統預先定義好的 ActionName,就能跳到系統的功能頁面,還能一併帶上資料:

package testIntent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class FirstActivity extends Activity implements OnClickListener {
    private Button toWeBButton, toPicButton, toMesButton, toPhoneButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_activity_main);
        toWeBButton = (Button) findViewById(R.id.toWeb);
        toPicButton = (Button) findViewById(R.id.toPic);
        toMesButton = (Button) findViewById(R.id.toMes);
        toPhoneButton = (Button) findViewById(R.id.toPhone);
        toWeBButton.setOnClickListener(this);
        toPicButton.setOnClickListener(this);
        toMesButton.setOnClickListener(this);
        toPhoneButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        if (v.equals(toWeBButton)) {          // 開啟網頁
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://www.baidu.com"));
        } else if (v.equals(toPicButton)) {   // 打開系統圖片
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else if (v.equals(toMesButton)) {   // 發送訊息
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, "這是我第一次這樣發信息");
        } else if (v.equals(toPhoneButton)) { // 撥打電話
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("tel:1839860592"));
        }
        startActivity(intent);
    }
}

透過這些系統 Action,就能輕鬆實現開網頁、選圖片、發訊息、撥電話等常見操作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved