Android基礎(四)自動服務1.獲取電池電量
阿新 • • 發佈:2018-12-13
xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:layout_width="50dp" android:layout_height="50dp" /> <ToggleButton android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/button" android:textOn="檢測當前手機電量" android:textOff="停止檢測"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/text"/> </LinearLayout>
java:
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.ToggleButton; import com.example.camera.R; public class MainActivity extends AppCompatActivity { private ToggleButton button; private TextView text; BroadcastReceiver receiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (ToggleButton) findViewById(R.id.button); text = (TextView) findViewById(R.id.text); final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { int current = intent.getExtras().getInt("level"); int total = intent.getExtras().getInt("scale"); int value = current * 100 / total; text.setText("當前電量是" + value + "%" + ""); } } }; button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) { IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(receiver, filter); } else { unregisterReceiver(receiver); text.setText(""); } } }); } }
- BroadcastReceiver 用於監聽與接收App發出的廣播訊息並作出響應
- onReceive 廣播接收器接收到相應廣播後,會自動回撥 onReceive() 方法
- CompoundButton.OnCheckedChangeListener() 可選中按鈕的是否選中方法
- registerReceiver(receiver, filter); 註冊廣播接收器