Android开发 使用广播实现每一分钟记录一次电量。

最近项目要求每一分钟记录一次手机的电量来统计手机的耗电量,这个就简单地使用广播来实现。

广播类如下:

package com.example.bluechatapp.Performance;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;

import com.example.bluechatapp.MainActivity.MainActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.example.bluechatapp.MusicActivity.MusicPlayerHelper.TAG;

public class BatteryReceiver extends BroadcastReceiver {
    private static int current ;
    private static int total ;
    private static float percent ;
    private static boolean first = false ;
    private static File electricityFile ;
    public BatteryReceiver() throws IOException {
        current = 0 ;
        total = 0 ;
        percent = 0 ;
        initSaveDirectory();
    }
    /**
     * 初始化保存目录
     */
    private void initSaveDirectory() throws IOException {
        File rootDir = new File(String.valueOf(Environment.getExternalStorageDirectory()),"EarMotion") ;
        if (!rootDir.exists()){
            rootDir.mkdirs() ;
        }
        File performanceDir = new File(rootDir.getPath(),"Performance") ;
        if (!performanceDir.exists()){
            performanceDir.mkdirs() ;
        }
        performanceDir = new File(performanceDir.getPath(),"battery") ;
        if (!performanceDir.exists()){
            performanceDir.mkdirs() ;
        }
        int length = performanceDir.listFiles().length + 1 ;
        electricityFile = new File(performanceDir.getPath(),(length+".txt"));
        if (!performanceDir.exists()){
            performanceDir.createNewFile() ;
        }
        OutputStream stream = new FileOutputStream(electricityFile,false) ;
        stream.write("Battery:\ntime\t\trest\n".getBytes() );
        stream.close() ;
    }
    @Override
    public void onReceive(Context context, Intent intent) {

       // 这个广播用来更新电量
        if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
            current = intent.getExtras().getInt("level");// 获得当前电量
            total = intent.getExtras().getInt("scale");// 获得总电量
            percent = current * 100 / total ;
            if (!first){
                Log.d(TAG, "当前电量 "+current+" 总电量"+total + " 百分比 " + percent);
                OutputStream battery;
                SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
                try {
                    battery = new FileOutputStream(electricityFile,true);
                    battery.write((df.format(new Date())+"\t"+current+"%\n").getBytes());
                    battery.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                first = true ;
            }
        }
        // 每一分钟系统将会发起这个广播,我们将电量写入文件
        if(intent.getAction().equals(Intent.ACTION_TIME_TICK)){
            Log.d(TAG, "当前电量 "+current+" 总电量"+total + " 百分比 " + percent);
            SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
            Log.d(TAG, "onReceive: "+df.format(new Date()));// new Date()为获取当前系统时间
            try {
                OutputStream battery = new FileOutputStream(electricityFile,true) ;
                battery.write((df.format(new Date())+"\t"+current+"%\n").getBytes());
                battery.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

使用方法

/**
     * 启动电量监视线程
     */
    public void startBatteryMonitor() throws IOException {
        BatteryReceiver receiver = new BatteryReceiver() ;
        IntentFilter filter=new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        // 注册广播
        context.registerReceiver(receiver,filter);
    }

最终结果
在这里插入图片描述

完结撒花!
欢迎大家在评论区中与我讨论!!谢谢大家的阅读!

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值