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

Android Intent 與 Uri 的常見用法:開網頁、撥號與頁面傳值

編輯:關於 Android 開發

Intent 搭配 Uri 的幾種典型場景

Intent 是 Android 四大組件之間溝通的橋樑,而當它與 Uri 結合時,就能輕鬆完成開啟網頁、撥打電話、跳轉頁面乃至於跨頁面傳遞資料等常見任務。以下整理幾個最實用的寫法。

1. 開啟網頁

// 打開百度
Uri uri = Uri.parse("https://www.baidu.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

2. 跳轉到另一個頁面

Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);

3. 撥打電話

// 撥打電話
Uri uri = Uri.parse("tel:10010");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
// 權限設置如下

若要直接撥號(而非僅開啟撥號介面),需在 AndroidManifest.xml 中加上通話權限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
 package="com.gis_luq.activitytest1" >
 <uses-permission android:name="android.permission.CALL_PHONE"/>
 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity
 android:name=".Main2Activity"
 android:label="@string/title_activity_main2" >
 </activity>
 </application>
</manifest>

4. 頁面間傳遞資料

Intent 可以透過 putExtra 或 Bundle 攜帶資料,目標頁面再用 getIntent 取出:

Intent intent = new Intent(MainActivity.this, Main2Activity.class);

intent.putExtra("yl1", "gisoracle");

// 用 Bundle 攜帶數據
Bundle bundle = new Bundle();
// 傳遞 name 參數為 tinyphp
bundle.putString("yl2", "我愛你桂霞");
intent.putExtras(bundle);
startActivity(intent);

在目標頁面 Main2Activity 中接收:

public class Main2Activity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main2);

 // 獲取 Intent 攜帶數據
 Intent intent = getIntent();
 String index = intent.getStringExtra("yl1");

 // 用 Bundle 攜帶數據
 Bundle bundle = getIntent().getExtras();
 String data = bundle.getString("yl2"); // 讀出數據

 Toast.makeText(this, index + "-" + data, Toast.LENGTH_SHORT).show();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved