当前位置:   article > 正文

android 广播监控手机电量_广播接收者监听电量小于15时

广播接收者监听电量小于15时

问题很简单 直接给出代码

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. tools:context=".MainActivity" >
  6. <LinearLayout
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:layout_centerInParent="true"
  10. android:orientation="vertical" >
  11. <TextView
  12. android:id="@+id/tv_cell"
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:text="电池电量"
  16. android:textColor="#000000"
  17. android:layout_margin="10dp"
  18. android:textSize="18dp" />
  19. </LinearLayout>
  20. </RelativeLayout>


监听需要权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

  1. package cn.itcast.BatteryChecker;
  2. import android.app.Activity;
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.IntentFilter;
  7. import android.net.ConnectivityManager;
  8. import android.net.NetworkInfo.State;
  9. import android.os.Bundle;
  10. import android.widget.TextView;
  11. import android.widget.Toast;
  12. public class MainActivity extends Activity {
  13. private TextView tv_cell;
  14. private BatteryReceiver batteryReceiver;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. tv_cell = (TextView) findViewById(R.id.tv_cell);
  20. // 注册广播接受者java代码
  21. IntentFilter intentFilter = new IntentFilter(
  22. Intent.ACTION_BATTERY_CHANGED);
  23. batteryReceiver = new BatteryReceiver();
  24. // 注册receiver
  25. registerReceiver(batteryReceiver, intentFilter);
  26. }
  27. /**
  28. * 广播接受者
  29. */
  30. private class BatteryReceiver extends BroadcastReceiver {
  31. @Override
  32. public void onReceive(Context context, Intent intent) {
  33. if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
  34. int level = intent.getIntExtra("level", 0);
  35. tv_cell.setText("电池电量为" + level + "%");
  36. if (level < 15) {
  37. Toast.makeText(MainActivity.this, "电池电量不足15%,请及时充电", 0)
  38. .show();
  39. }
  40. }
  41. }
  42. }
  43. @Override
  44. protected void onDestroy() {
  45. super.onDestroy();
  46. unregisterReceiver(batteryReceiver);
  47. }
  48. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/902031
推荐阅读
相关标签
  

闽ICP备14008679号