Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách phát hiện thay đổi chế độ Máy bay trên Android

Giới thiệu

Ví dụ này minh họa cách phát hiện khi người dùng bật/tắt chế độ Máy bay bằng BroadcastReceiver lắng nghe Intent.ACTION_AIRPLANE_MODE_CHANGED.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    private BroadcastReceiver mMessageReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);

        mMessageReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean isAirplaneMode = android.provider.Settings.Global.getInt(
                        context.getContentResolver(),
                        android.provider.Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
                textView.setText(isAirplaneMode ? "Chế độ Máy bay: BẬT" : "Chế độ Máy bay: TẮT");
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mMessageReceiver, new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mMessageReceiver);
    }
}

Khác với bài trước (ID 1003061233) chỉ kiểm tra trạng thái lúc mở app, bài này lắng nghe realtime khi người dùng thay đổi chế độ máy bay.

Chạy ứng dụng

Mở app, sau đó kéo thanh thông báo bật/tắt chế độ máy bay. TextView cập nhật ngay lập tức.

Cách phát hiện thay đổi chế độ Máy bay trên Android