如何在 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"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://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>在上述代码中,我们已取文本视图以显示设备飞行模式状态。
第 3 步 − 添加以下代码到 src/MainActivity.java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import static android.os.BatteryManager.ACTION_CHARGING;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
}
@Override
protected void onStop() {
super.onStop();
MainActivity.this.unregisterReceiver(mMessageReceiver);
}
@Override
protected void onResume() {
super.onResume();
MainActivity.this.registerReceiver(mMessageReceiver, new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
textView.setText("Device airplane mode is changed");
}
};
}我们尝试运行您的应用程序。我假设您已将实际的 Android 移动设备连接到计算机。要从 Android Studio 运行该应用,请打开您项目的一个活动文件,然后点击工具栏上的运行
图标。选择您的移动设备作为一项选项,然后查看您的移动设备,它将会显示您的默认屏幕 –

点击 此处 下载项目代码
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
JavaScript
PHP