Android: Intent và Intent-Filter trong Android

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

Intent trong Android

Một Intent trong Android là một miêu tả trừu tượng của một hoạt động để được thực hiện. Nó có thể được sử dụng với startActivity để chạy một ActivitybroadcastIntent để gửi nó tới bất kỳ thành phần BroadcastReceiver nào quan tâm đến, và với startService(Intent) hoặc bindService(Intent, ServiceConnection, int) để giao tiếp với một Service ở Background.

Bản chất của Intent là một cấu trúc dữ liệu thụ động giữ một miêu tả trừu tượng của một hành động để được thực thi.

Ví dụ, giả sử rằng bạn có một Activity cần chạy một Email client và gửi một Email sử dụng thiết bị Android. Với mục đích này, Activity của bạn sẽ gửi một ACTION_SEND cùng với Chooser thích hợp, tới Android Intent Resolver. Chooser đã cho cung cấp giao diện thích hợp cho người dùng để lựa chọn cách gửi dữ liệu Email của họ.

Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
startActivity(Intent.createChooser(email, "Chn mt email t..."));

Cú pháp trên đang gọi phương thức startActivity để bắt đầu một Email activity và kết quả như sau:

Intent trong Android

Ví dụ, giả sử bạn có một Activity mà cần mở URL trong một trình duyệt web trên thiết bị Android. Với mục đích này, Activity của bạn sẽ gửi ACTION_WEB_SEARCH Intent tới Android Intent Resolver để mở URL đã cho trong trình duyệt web. Intent Resolver này phân tích cú pháp qua một danh sách các Activity và lựa chọn một cái tốt nhất cho Intent của bạn, trong trường hợp này là Web Browser Activity. Sau đó, Intent Resolver truyền trang web tới trình duyệt và bắt đầu Web Browser Activity.

String query = "v1study";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, query);
startActivity(intent);

Ví dụ trên sẽ tìm v1study trên thiết bị tìm kiếm của Android và nó sẽ cho kết quả trong một Activity.

Có một số kỹ thuật riêng rẽ để phân phối các Intent tới mỗi loại thành phần như Activity, Service và BroadcastReceiver.

Stt Phương thức & Miêu tả
1 Context.startActivity()

Đối tượng Intent được truyền tới phương thức này để chạy một Activity mới hoặc lấy một Activity đang tồn tại để làm cái gì đó mới

2 Context.startService()

Đối tượng Intent được truyền tới phương thức này để khởi tạo một Service hoặc phân phối các chỉ thị mới tới một Service đang chạy

3 Context.sendBroadcast()

Đối tượng Intent được truyền tới phương thức này để phân phối thông báo tới tất cả BroadcastReceiver cần quan tâm

Các đối tượng Intent trong Android

Một đối tượng Intent là một gói thông tin được sử dụng bởi thành phần nhận được Intent đó cũng như thông tin được sử dụng bởi hệ điều hành Android.

Một đối tượng Intent có thể chứa các thành phần sau dựa vào những gì nó giao tiếp hoặc đang chuẩn bị thực hiện:

Action

Đây là phần bắt buộc của đối tượng Intent và là một chuỗi đặt tên action để được thực hiện, hoặc trong trường hợp các Broadcast Intent, thì đó là action đã diễn ra và đang được báo cáo. Action quyết định cách mà phần còn lại của đối tượng Intent được cấu trúc. Lớp Intent định nghĩa một số hằng action tương ứng với các Intent khác nhau. Bạn theo link sau để có danh sách các Standard Action trong Android.

Action trong một đối tượng có thể được thiết lập bởi phương thức setAction() và được đọc bởi getAction().

Data

Là dữ liệu được sử dụng trong một Action. Nó thêm một kiểu dữ liệu (thuộc tính mimeType), một URI, hoặc cả kiểu dữ liệu và URI tới một Intent Filter. Một URI được xác định bởi các thuộc tính riêng rẽ cho mỗi phần của nó.

Các thuộc tính này, xác định định dạng của URL, là tùy ý, nhưng chúng cũng có thể phụ thuộc vào:

  • Nếu một Scheme không được xác định cho Intent-Filter, thì tất cả thuộc tính URI khác bị bỏ qua.
  • Nếu một Host không được xác định cho Intent Filter, thì thuộc tính port và tất cả thuộc tính path bị bỏ qua.

Phương thức setData() xác định dữ liệu chỉ ở dạng như một URI, phương thức setType() xác định nó chỉ ở dạng một kiểu MIME, và setDataType() xác định nó với cả hai dạng là URI và một kiểu MIME. URI được đọc bởi getData() và kiểu được đọc bởi getType().

Bảng dưới liệt kê một số ví dụ về các cặp action/data:

Stt Cặp Action/Data & Miêu tả
1 ACTION_VIEW content://contacts/people/1

Hiển thị thông tin về người có định danh là "1"

2 ACTION_DIAL content://contacts/people/1

Hiển thị phone dialer với người đã được điền vào trong

3 ACTION_VIEW tel:123

Hiển thị phone dialer với số đã được điền vào

4 ACTION_DIAL tel:123

Hiển thị phone dialer với số đã được điền vào

5 ACTION_EDIT content://contacts/people/1

Chỉnh sửa thông tin về người có định danh là "1"

6 ACTION_VIEW content://contacts/people/

Hiển thị danh sách people mà người dùng có thể duyệt qua đó

7 ACTION_SET_WALLPAPER

Hiển thị thiết lập để lựa chọn wallpaper

8 ACTION_SYNC

Đồng bộ hóa dữ liệu, Constant Value là android.intent.action.SYNC

9 ACTION_SYSTEM_TUTORIAL

Bắt đầu phần hướng dẫn mặc định (đã được định nghĩa trước)

10 ACTION_TIMEZONE_CHANGED

Nó thông báo khi Timezone đã thay đổi

11 ACTION_UNINSTALL_PACKAGE

Được sử dụng để chạy Uninstaller

Category trong Android

Category là một phần tùy ý của đối tượng Intent và nó là một chuỗi chứa thông tin bổ sung về loại thành phần nên xử lý Intent đó. Phương thức addCategory() đặt một Category trong một đối tượng Intent, phương thức removeCategory() xóa một Category đã được thêm trước đó, và phương thức getCategories() lấy tập hợp các Category hiện tại trong đối tượng. Bạn theo link sau để có một danh sách Intent Standard Category trong Android.

Bạn có thể kiểm tra chi tiết về Intent Filter ở phần dưới để hiểu cách chúng ta sử dụng Category để lựa chọn Activity thích hợp với một Intent.

Extras

Đây là cặp key-value cho thông tin bổ sung mà sẽ được phân phối tới thành phần xử lý Intent đó. Extras có thể được thiết lập và được đọc bằng cách sử dụng tương ứng hai phương thức là putExtras() và getExtras(). Bạn theo link sau để có danh sách Intent Standard Extra trong Android.

Flags

Các Flags này là phần tùy ý của đối tượng Intent và chỉ thị hệ điều hành Android cách chạy một Activity, và cách xử lý sau khi nó đã chạy, …

Stt Flag & Miêu tả
1 FLAG_ACTIVITY_CLEAR_TASK

Nếu thiết lập trong một Intent được truyền tới Context.startActivity(), thì flag này sẽ làm cho bất cứ tác vụ nào đang tồn tại, mà được gắn kết với Activity, bị xóa trước khi Activity đó được bắt đầu. Đó là, Activity đó trở thành Root mới của một tác vụ trống, và bất kỳ Activity cũ nào bị kết thúc. Điều này chỉ có thể được sử dụng khi kết hợp với FLAG_ACTIVITY_NEW_TASK

2 FLAG_ACTIVITY_CLEAR_TOP

Nếu được thiết lập, và Activity đang được chạy là đã chạy trong tác vụ hiện tại, thì thay vì chạy sự thể hiện mới của Activity đó, tất cả Activity khác ở trên nó sẽ bị đóng và Intent này sẽ được phân phối tới Activity cũ (ngay trên) như là một Intent mới

3 FLAG_ACTIVITY_NEW_TASK

Nói chung, Flag này được sử dụng bởi các Activity mà muốn có mặt một hành vi "launcher": chúng cung cấp cho người dùng một danh sách các mục riêng rẽ để có thể được thực hiện, mà có thể chạy hoàn toàn độc lập với Activity đang chạy chúng

Component Name trong Android

Trường tùy ý này là một đối tượng ComponentName trong Android để biểu diễn lớp Activity, Service, hoặc lớp BroadcastReceiver. Nếu nó được thiết lập, đối tượng Intent được phân phối tới một sự thể hiện của lớp đã chỉ định, nếu không thì Android sử dụng thông tin khác trong đối tượng Intent để xác định vị trí một mục tiêu phù hợp.

Component Name được thiết lập bởi setComponent(), setClass() hoặc setClassName() và được đọc bởi getComponent().

Các loại Intent trong Android

Android hỗ trợ hai loại Intent:

Intent trong Android

Các đối tượng Explicit Intent trong Android

Explicit Intent được kết nối với thế giới bên trong của ứng dụng, giả sử nếu bạn muốn kết nối một Activity tới Activity khác, chúng ta có thể thực hiện điều này bởi Explicit Intent. Hình ảnh sau kết nối Activity đầu tiên với Activity thứ hai bằng việc nhấn vào nút.

Intent trong Android

Các Intent này chỉ rõ thành phần target bằng tên của nó và chúng đặc biệt được sử dụng cho các thông báo nội bộ ứng dụng, như việc một Activity bắt đầu một Service của nó. Ví dụ:

// Explicit Intent bng cách xác đnh tên lp ca nó
Intent i = new Intent(FirstActivity.this, SecondAcitivity.class);

// Kích hot TargetActivity
startActivity(i);

Các đối tượng Implicit Intent trong Android

Có thể gọi là Intent ngầm định. Chúng không đặt tên mục tiêu và trường cho tên thành phần trống. Các Implicit Intent thường được sử dụng để kích hoạt các thành phần trong ứng dụng khác. Ví dụ:

Intent read1=new Intent();
read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);

Thành phần target mà nhận Intent này có thể sử dụng phương thức getExtras() để lấy dữ liệu Extras được gửi bởi thành phần source. Ví dụ:

// Ly gói đi tượng  v trí riêng trong code
Bundle extras = getIntent().getExtras();

// Extract d liu dùng các key đã được truyn đi
String value1 = extras.getString("Key1");
String value2 = extras.getString("Key2");

Ví dụ áp dụng

Ví dụ sau minh họa tính năng của một Intent trong Android để chạy các ứng dụng có sẵn trong Android.

Bước Miêu tả
1 Bạn sử dụng Android Studio IDE để tạo một ứng dụng Android có tên là IntentV1Study dưới một package v1study.com.intentv1study.Trong khi tạo project này, đảm bảo Target SDK và Compile With là tại phiên bản mới nhất của Android SDK để sử dụng các APIs cấp độ cao hơn
2 Sửa đổi src/main/java/MainActivity.java và thêm code để định nghĩa hai Listener tương ứng với hai nút là Start Browser và Start Phone
3 Sửa đổi res/layout/activity_main.xml để thêm 3 nút trong linear layout
4 Chạy ứng dụng để chạy Android Emulator và kiểm tra kết quả các thay đổi đã thực hiện trong ứng dụng

Sau đây là nội dung của file MainActivity.java:

package v1study.com.intentv1study;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
  Button btnStartBrowser, btnStartPhone;
  EditText editTextURLPhone;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStartBrowser = findViewById(R.id.btnStartBrowser);
    btnStartPhone = findViewById(R.id.btnStartPhone);
    editTextURLPhone = findViewById(R.id.editTextURLPhone);
    btnStartBrowser.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(editTextURLPhone.getText().toString()));
        startActivity(i);
      }
    });
    btnStartPhone.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(editTextURLPhone.getText().toString()));
        startActivity(i);
      }
    });
  }
}

Nội dung của file res/layout/activity_main.xml là:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

  <TextView
    android:id="@+id/txtView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/intent_trong_android"
    android:textColor="#8BC34A"
    android:textSize="30sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.096"/>

  <ImageView
    android:id="@+id/imageView"
    android:layout_width="170dp"
    android:layout_height="170dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:contentDescription="@string/v1studylogo"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.258"
    app:srcCompat="@mipmap/logo_v1_regular"/>

  <EditText
    android:id="@+id/editTextURLPhone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autofillHints=""
    android:hint="@string/enter_url_or_phone_number"
    android:inputType="text|phone"
    android:textColor="#8BC34A"
    android:textSize="25sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.62"/>

  <Button
    android:id="@+id/btnStartBrowser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/start_browser"
    android:textColor="#8BC34A"
    android:textSize="30sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.524"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.725"/>

  <Button
    android:id="@+id/btnStartPhone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/start_phone"
    android:textColor="#8BC34A"
    android:textSize="30sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.84"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Nội dung của res/values/strings.xml là:

<resources>
  <string name="app_name">IntentV1Study</string>
  <string name="intent_trong_android">Intent trong Android</string>
  <string name="v1study">V1Study</string>
  <string name="v1study_logo">V1Study Logo</string>
  <string name="start_browser">Start Browser</string>
  <string name="start_phone">Start Phone</string>
  <string name="enter_url_or_phone_number">Enter URL or Phone number</string>
  <string name="v1studylogo">V1Study Logo</string>
</resources>

 

Chạy ứng dụng Android sẽ ra màn hình như sau:

Intent trong Android

Bạn hãy điền vào phần EditText một URL (https://v1study.com chẳng hạn) hoặc một số điện thoại rồi nhấn nút tương ứng ở phía dưới:

Điền URL vào EditText

Kết quả được thể hiện như hình dưới:

Kết quả chạy chương trình với Intent

Intent-Filter trong Android

Bạn đã thấy cách một Intent được sử dụng để gọi một Activity khác. Hệ điều hành Android sử dụng các Filter để định vị tập hợp các Activity, Service và BroadcastReceiver mà có thể xử lý Intent với sự giúp đỡ của một tập đã cho các Action, Category, Data Sheme gắn kết với một Intent. Bạn sẽ sử dụng phần tử <> trong manifest file để liệt kê các Action, Category, Data Sheme gắn kết với bất cứ Activity, Service hay BroadcastReceiver nào.

Sau đây là một ví dụ của một phần AndroidManifest.xml để xác định một Activity là v1study.com.intentfilter.CustomActivity có thể được triệu hồi bởi một trong hai Action ở trên, một Category, và một Data.

<activity
  android:name=".CustomActivity"
  android:label="@string/app_name">

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <action android:name="com.example.My Application.LAUNCH" />
  <category android:name="android.intent.category.DEFAULT" />
  <data android:scheme="https" />
</intent-filter>

</activity>

Khi Activity này được định nghĩa cùng với Filter ở trên, thì các Activity khác sẽ có thể triệu hồi Activity này bằng cách sử dụng android.intent.action.VIEW, hoặc sử dụng action v1study.com.intentv1study.MyApplication.LAUNCH đã cung cấp category của nó là android.intent.category.DEFAULT.

Phần tử <data> xác định kiểu dữ liệu được mong đợi bởi Activity để được gọi và với ví dụ trên, thì Custom Activity của chúng ta mong muốn dữ liệu bắt đầu với "https://"

Có một tình huống mà một Intent có thể truyền thông qua các Filter của nhiều hơn một Activity hoặc Service, đó là người dùng có thể được hỏi xem muốn kích hoạt thành phần nào. Một Exception sẽ được tạo ra nếu không tìm thấy mục tiêu nào.

Android sẽ kiểm tra một số test sau trước khi triệu hồi một Activity:

  • Một <intent-filter> <> có thể liệt kê nhiều hơn một Action như ở trên nhưng list này không thể là trống; một Filter phải chứa ít nhất một phần tử <action> nếu không thì nó sẽ chặn tất cả Intent. Nếu có nhiều hơn một Action được đề cập, thì Android cố gắng kết nối một trong những Action đó trước khi triệu hồi Activity.
  • Một <intent-filter>có thể liệt kê 0, 1, hoặc nhiều hơn một Category. Nếu không có Category nào được đề cập, thì Android luôn luôn truyền test này nhưng nếu có nhiều hơn một Category được đề cập thì cho một Intent để truyền Category test, mỗi Category trong đối tượng Intent phải kết nối một Category trong Filter.
  • Mỗi phần tử <data> có thể xác định một URI và một kiểu dữ liệu (kiểu MIME). Có các thuộc tính riêng biệt như scheme, host, port và path cho mỗi phần của URI. Một đối tượng Intent mà chứa cả URI và kiểu dữ liệu thì truyền phần kiểu dữ liệu của test chỉ khi kiểu của nó kết nối với một kiểu được liệt kê trong Filter.

Ví dụ

Ví dụ sau ta sẽ thấy cách Android xử lý xung đột nếu một Intent đang triệu hồi hai Activity được định nghĩa trong nó, kế tiếp là cách để triệu hồi một Custom Activity bằng cách sử dụng một Filter và tiếp nữa là một Exception nếu Android không tìm thấy Activity thích hợp đã định nghĩa cho một Intent.

Nội dung của file MainActivity.java:

package v1study.com.intentfilter;

import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
  Button buttonViewAction, buttonLaunchAction, buttonExceptionalCondition;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonViewAction = findViewById(R.id.buttonViewAction);
    buttonViewAction.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://v1study.com"));
        startActivity(i);
      }
    });

    buttonLaunchAction = findViewById(R.id.buttonLaunchAction);
    buttonLaunchAction.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent i = new Intent("v1study.com.intentfilter.LAUNCH", Uri.parse("https://v1study.com"));
        startActivity(i);
      }
    });

    buttonExceptionalCondition = findViewById(R.id.buttonExceptionalCondition);
    buttonExceptionalCondition.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent i = new Intent("v1study.com.intentfilter.LAUNCH", Uri.parse("http://v1study.com"));
        startActivity(i);
      }
    });
  }
}

Nội dung của file CustomActivity.java nằm cùng vị trí với MainActivity.java:

package v1study.com.intentfilter;

import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class CustomActivity extends AppCompatActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.custom_view);

    TextView showData=findViewById(R.id.showData);
    Uri uri=getIntent().getData();
    showData.setText(uri.toString());
  }
}

Nội dung của file res/layout/activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  xmlns:android="http://schemas.android.com/apk/res/android">

  <TextView
    android:id="@+id/textView1"
    android:text="@string/intent_filter_example"
    android:textSize="30sp"
    android:textStyle="bold"
    android:textColor="#4CAF50"
    android:layout_height="50dp"
    android:layout_width="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintVertical_bias="0.052"/>

  <EditText
    android:layout_width="293dp"
    android:layout_height="47dp"
    android:id="@+id/editText"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.562"
    android:hint="@string/input_here"
    android:inputType="text"
    android:importantForAutofill="no"/>

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/start_browsing_with_view_action"
    android:id="@+id/buttonViewAction"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.496"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.915"/>
  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/start_browsing_with_launch_action"
    android:id="@+id/buttonLaunchAction"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.452"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.815"/>

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/exceptional_condition"
    android:id="@+id/buttonExceptionalCondition"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.714"
    app:layout_constraintHorizontal_bias="0.509"/>

  <ImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    app:srcCompat="@drawable/logo_v1study"
    android:id="@+id/imageViewLogo"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintVertical_bias="0.218"
    android:contentDescription="@string/logo"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Nội dung của file res/layout/custom_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:orientation="vertical"
  android:layout_height="match_parent"
  android:layout_width="match_parent"
  xmlns:android="http://schemas.android.com/apk/res/android">

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/showData"/>
</LinearLayout>

Tiếp theo là nội dung của file res/values/strings.xml:

<resources>
  <string name="app_name">IntentFilterV1Study</string>
  <string name="exceptional_condition">Exceptional condition</string>
  <string name="logo_v1study">Logo V1Study</string>
  <string name="start_browsing_with_view_action">Start browsing with view action</string>
  <string name="start_browsing_with_launch_action">Start browsing with launch action</string>
  <string name="intent_filter_example">Intent-Filter Example</string>
  <string name="input_here">Input here</string>
  <string name="logo">Logo V1Study</string>
</resources>

Và đây là nội dung của file AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools" package="v1study.com.intentfilter">

  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>

        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>

    <activity
      android:name=".CustomActivity"
      android:label="Intent-Filter">
      <intent-filter tools:ignore="AppLinkUrlError">
        <action android:name="android.intent.action.VIEW"/>
        <action android:name="v1study.com.intentfilter.LAUNCH"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:scheme="https"/>
      </intent-filter>
    </activity>

  </application>

</manifest>

Chạy ứng dụng Android ta được giao diện như sau:

Intent-Filter trong Android

Bây giờ, bắt đầu với button đầu tiên "Start Browsing with VIEW Action". Ở đây, chúng ta đã định nghĩa Custom Activity với một Filter là Intent.ACTION_VIEW, và đã có một Activity mặc định với VIEW action được định nghĩa bởi Android đang chạy trình duyệt web. Vì thế, Android hiển thị hai tùy chọn sau để lựa chọn Activity bạn muốn chạy.

Intent trong Android

Bây giờ, nếu bạn chọn Chrome thì Android sẽ chạy trình duyệt web và mở https://v1study.com, nhưng nếu bạn lựa chọn IndentFilterV1Study thì Android sẽ chạy CustomActivity mà không thực hiện bất cứ điều gì, chỉ bắt dữ liệu đã truyền và hiển thị dưới dạng Text View như sau:

Intent-Filter trong Android

Bây giờ ta nhấn nút Back để quay lại, sau đó nhấn chọn nút "Start Browsing with LAUNCH Action", ở đây Android áp dụng Filter để lựa chọn Activity và nó sẽ chạy CustomActivity của ta.

Một lần nữa, nhấn nút back và nhấn nút "Exceptional Condition", ở đây Android cố gắng tìm một Filter hợp lệ cho Intent đã cho nhưng nó không tìm một Activity hợp lệ đã được định nghĩa bởi vì lúc này chúng ta đã sử dụng dữ liệu dạng http thay vì https. Vì thế, dù cho chúng ta đang cung cấp một Action đúng, thì Android tạo một Exception và hiển thị màn hình sau:

Intent trong Android

» Tiếp: LinearLayout trong Android
« Trước: Fragment trong Android
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!