如何在 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_POWER_CONNECTED));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
textView.setText("Device power is connected");
}
};
}讓我們嘗試執行你的應用程式。我假設你已將你的 Android 移動裝置與電腦連線。要從 Android Studio 執行該應用程式,開啟一個專案的活動檔案,並單擊工具欄上的執行圖示
。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕 –

單擊 此處 下載專案程式碼
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP