Android 應用程序電量監控

Android電量監控主要思想 就利用Intent.ACTION_BATTERY_CHANGED監控電量的變化,用廣播進行接收 ,但是目前我還沒有一個好的辦法能監控到每個應用分別耗電是多少,還有算出電池的容量有多少mAh,如果有這方面研究的,希望學習一下
下面代碼是主要的Activity
package com.example.batteryproject04;
import android.app.Activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
	private Button but = null;
	public void onCreate(Bundle savedInstanceState) {    
		super.onCreate(savedInstanceState);   
		setContentView(R.layout.activity_main);  
		IntentFilter intent = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		MainActivity.this.registerReceiver(BatteryStart.getInstance(),intent);
		}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {			
		menu.add(Menu.NONE, 									
				Menu.FIRST + 1, 								
				5, 												
				"关闭")											
				.setIcon(android.R.drawable.btn_default);	
		return true;											
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {		
		switch (item.getItemId()) {								
		case Menu.FIRST + 1:
			break;
		}
		return false;
	}
	 @Override  
	    public boolean onKeyDown(int keyCode, KeyEvent event)  
	    {  
	        if (keyCode == KeyEvent.KEYCODE_BACK )  
	        { 
	            // 创建退出对话框  
	            AlertDialog isExit = new AlertDialog.Builder(this).create();  
	            // 设置对话框标题  
	            isExit.setTitle("系统提示");  
	            // 设置对话框消息  
	            isExit.setMessage("确定要退出吗");  
	            // 添加选择按钮并注册监听  
	            isExit.setButton("确定", listener);  
	            isExit.setButton2("取消", listener);  
	            // 显示对话框  
	            isExit.show();  
	        }  
	        return false;    
	    }  
	    /**监听对话框里面的button点击事件*/  
	    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()  
	    {  
	        public void onClick(DialogInterface dialog, int which)  
	        {  
	            switch (which)  
	            {  
	            case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序  
	            	BatteryStart.getInstance().j=0;
	            	IntentFilter intent = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
	        		MainActivity.this.registerReceiver(BatteryStart.getInstance(),intent);
	                finish();  
	                break;  
	            case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框  
	                break;  
	            default:  
	                break;  
	            }  
	        }  
	    };    
}

下面代碼是寫入SD卡的

 import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import android.content.Context; import android.os.Environment; import android.widget.Toast;

public class CheckBattery { /*  * *存储日志文件  */ public void SavedToText(String stringToWrite){   //判断SD卡是否存在   if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {    String foldername = Environment.getExternalStorageDirectory().getPath()+ "/battery";       File folder = new File(foldername);             if (folder == null || !folder.exists()) {        folder.mkdir();       }       String fileName="/battery_check"+".txt";        File targetFile = new File(foldername + fileName);    OutputStreamWriter osw;     try{     if(!targetFile.exists()){      targetFile.createNewFile();      osw = new OutputStreamWriter(new FileOutputStream(targetFile),"utf-8");      osw.write("                  Android application power monitoring \r\n");      osw.write(stringToWrite);       osw.close();     }else{      osw = new OutputStreamWriter(new FileOutputStream(targetFile,true),"utf-8");      osw.write("\r\n"+stringToWrite);      osw.flush();      osw.close();     }     } catch (Exception e) {     //Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();     }   }else{    //Toast.makeText(context,"未发现SD卡!",Toast.LENGTH_LONG).show();   }               }

}

下面代碼是一個廣播接收器
package com.example.batteryproject04;

import java.util.Calendr; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BatteryStart extends BroadcastReceiver{ public static int i=0;    //i=0 表示为第一次启动 public static int j=1;    //判断关闭 1 表示未关闭  0 表示关闭 /*   * 运用单例模式   * 在每次打开应用程序都使用一个单例对象   * 这样省内存空间   * 使用时只需要Battery.getInstance()   * */ private static BatteryStart uniqueInstance = null;     private BatteryStart() {     }     public static BatteryStart getInstance() {        if (uniqueInstance == null) {            uniqueInstance = new BatteryStart();        }        return uniqueInstance;     }     /*      * 广播接收,当电量发生改变的时候,会广播到此接收器      * */ @Override public void onReceive(Context context, Intent intent) {   if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){    //判断电量是否发生变化    if(i==0){                                                    //第一次启动     int level1 = intent.getExtras().getInt("level");     String info = "---------------------------------------------\r\n"+     "启动应用程序当前电量:"+level1+"           "+        Calendar.getInstance().getTime();     new CheckBattery().SavedToText(info);                   //将文件写入SD卡     i=1;                                                    //修改标识位  改为 1 表示已经启动    }else if(j==0){                                             //关闭程序     int level2 = intent.getExtras().getInt("level");     String info = "关闭应用程序当前电量:"+level2+"           "+Calendar.getInstance().getTime()+        "\r\n---------------------------------------------";     new CheckBattery().SavedToText(info);                  //写入SD卡     j=1;                                                  //修改标识位     i=0;                                                  //修改标识位    }else    {    /*     * 记录程序启动过程中应用程序的耗电量情况     * */    int level = intent.getExtras().getInt("level");         //取得电量信息    String info2 = "    当前电池电量:"+level+"            "+Calendar.getInstance().getTime();    new CheckBattery().SavedToText(info2);                  //写入SD卡    }   }    } }

 

你可能感兴趣的:(android,battery,電量監控)