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);
    }

最终结果
Android开发 使用广播实现每一分钟记录一次电量。_第1张图片

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

你可能感兴趣的:(Android,Java,android,java)