监听wifi从上次未充电时开始计算各个app wifi 电池使用时间

本文介绍了一种在Android设备上实现电量监控及各应用程序使用时间记录的方法。通过注册广播接收器,可以监听电池电量变化、WiFi状态变化及热点开关状态,并记录开机以来的电量和WiFi使用时长。此外,还介绍了如何利用UsageStatsManager API获取各个应用的使用时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Launcher.java中  oncreate()中 获取上次从充电状态结束时的时间和获取电量

注册一个监听开机完成广播

/*获取电池电量信息 20180523 begin*/

        registerReceiver(mBootCompleted, new IntentFilter(   
         "android.intent.action.BOOT_COMPLETED")); 

        /*获取电池电量信息 20180523 end*/


/*获取电池电量信息  20180523 begin*/
// 创建BroadcastReceiver   BOOT_COMPLETED
private BroadcastReceiver mBootCompleted = new BroadcastReceiver() {   


@Override   
public void onReceive(Context context, Intent intent) {   
// TODO Auto-generated method stub   
String action = intent.getAction();   
// 如果捕捉到action是ACRION_BATTERY_CHANGED   
// 就运行onBatteryInfoReveiver()   
if (("android.intent.action.BOOT_COMPLETED").equals(action)) {   
registerReceiver(mBatInfoReveiver, new IntentFilter(   
                Intent.ACTION_BATTERY_CHANGED)); //注册一个监听电池电量信息  
}   
}   
}; 
private BroadcastReceiver mBatInfoReveiver = new BroadcastReceiver() {   


@Override   
public void onReceive(Context context, Intent intent) {   
// TODO Auto-generated method stub   
String action = intent.getAction();   
// 如果捕捉到action是ACRION_BATTERY_CHANGED   
// 就运行onBatteryInfoReveiver()   
if (intent.ACTION_BATTERY_CHANGED.equals(action)) {
int plugType = intent.getIntExtra("plugged", 0);
int i = Settings.System.getInt(getContentResolver(),"Batterystatus", 0);
Log.i("WifiReceiver", "7214plugType ="+plugType+ " i ="+ i);
if(plugType ==0) {//未充电

if(i == 0) {
int intLevel = intent.getIntExtra("level", 0);   
onBatteryInfoReceiver(intLevel); 
Settings.System.putInt(getContentResolver(),"Batterystatus", 1);
Settings.System.putString(getContentResolver(),"Batterylasttime", getCurrent());
Settings.System.putString(getContentResolver(),"lasttime", getwifilast());
Settings.System.putLong(getContentResolver(),"wifitotal", 0l);
}
}else {
if(i == 1) {
Log.i("WifiReceiver", "7227plugType ="+plugType+ " i ="+ i);
Settings.System.putInt(getContentResolver(),"Batterystatus", 0);
}
}
 

}   

}; 

private void onBatteryInfoReceiver(int intLevel) {   
// TODO Auto-generated method stub   
// 是否在充电
Settings.System.putInt(getContentResolver(),"BIRD_BATTERY", intLevel);


}
public String  getCurrent() {

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());


return simpleDateFormat.format(date);


}
public String  getwifilast() {

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("a hh:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());


return simpleDateFormat.format(date);


}

第二步监听wifi使用时间:WifiReceiver、


    /**
 * 该类是用于实时监测WiFi状态以及热点开关变化
 */
public class WifiReceiver extends BroadcastReceiver{
static final String TAG = "WifiReceiver";
Long wifitotal = 0L ;
String wifion ;


Boolean iswifioff = true ;
Boolean iswifion = false ;
Boolean iswifistart = false ;
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
String wifiname, WifiTotalTime,starttime;
String WifilastTime = "" ;


@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
String action = intent.getAction();
if(action.equals(WifiManager.RSSI_CHANGED_ACTION)){
//signal strength changed
}else if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){//wifi连接上与否
//System.out.println("网络状态改变");


NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
//Log.i(TAG, "5050info="+info.getState()); 
//2、获取WifiManager
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
wifiname = wifiInfo.getSSID();




//3、开启、关闭wifi
if(wifiManager.isWifiEnabled()) {
if(info.getState().equals(NetworkInfo.State.CONNECTED)) {
//Log.i(TAG, "3333     >>>>iswifioff="+Settings.System.getInt(context.getContentResolver(),"wifioff", 0));
//iswifioff = false ;
iswifistart = false ;
//获取当前wifi名称
if(Settings.System.getInt(context.getContentResolver(),"wifion", 0)!=1) {


Settings.System.putString(context.getContentResolver(),"lasttime", getwifilast());
Log.i(TAG, "7070     >>>>iswifioff="+iswifioff);
Settings.System.putInt(context.getContentResolver(),"wifion", 1);
Settings.System.putInt(context.getContentResolver(),"wifioff", 0);
}
iswifioff = false ;
}
}
else{
WifilastTime = Settings.System.getString(context.getContentResolver(),"lasttime");
if(info.getState().equals(NetworkInfo.State.DISCONNECTED)&&WifilastTime.length()>0){


if(Settings.System.getInt(context.getContentResolver(),"wifioff", 0)!=1) {
Log.i(TAG, "8989    WifilastTime= "+WifilastTime+"    getCurrent="+getCurrent());
iswifioff = true ;
Settings.System.putInt(context.getContentResolver(),"wifion", 0);
Settings.System.putInt(context.getContentResolver(),"wifioff", 1);//WifiToalTime
Settings.System.putString(context.getContentResolver(),"wifitime",  computingTime(context ,WifilastTime,getCurrent(),true));//wifi 使用的总时间
Log.i(TAG, "9393    WifiTotalTime= "+computingTime(context ,WifilastTime,getCurrent(),true));

}




}
}


}
else if("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)){
//便携式热点的状态为:10---正在关闭;11---已关闭;12---正在开启;13---已开启
int state = intent.getIntExtra("wifi_state",  0);
if(state == 12) {//正在开启
final AlertDialog alert = new AlertDialog.Builder(context)  
.create();  


alert.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);//广播中加入  才会弹框 
alert.setMessage("WLAN热点功能不可用");
alert.show();  


new Handler().postDelayed(new Runnable() {  
@Override  
public void run() {  
alert.dismiss();  
}  
}, 2000);  
}
if(state == 13){
//System.out.println("热点已开启");


closeWifiAp(context);


}
if(state == 11){

//  System.out.println("热点已关闭");
}
}else if (action.equals("android.intent.action.BOOT_COMPLETED")) { //开机启动完成后,要做的事情 
//开机电量


Log.i(TAG, "131    ");
if (wifiManager.isWifiEnabled()) {
iswifistart = true ;
/*Settings.System.getInt(context.getContentResolver(),
               Settings.System.VIBRATE_WHEN_RINGING, 0) != 0*/


Settings.System.putInt(context.getContentResolver(),"iswifistate", 0);


}else {
Settings.System.putInt(context.getContentResolver(),"iswifistate", 1);


}
Settings.System.putString(context.getContentResolver(),"lasttime", getwifilast());
Settings.System.putLong(context.getContentResolver(),"wifitotal", 0l);
Settings.System.putString(context.getContentResolver(),"Batterylasttime", getCurrent());

}  
}







/**
* 关闭WiFi热点
*/
public void closeWifiAp(Context context) {
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
try {
wifiManager.setWifiApEnabled(null, false);



} catch (Exception e) {
e.printStackTrace();
}


}




/**
* 计算两个时间差
*
* @param oldTime 开始时间
* @param nowTime 结束时间
* @return
*/
public String computingTime(Context context ,String takeTime, String presentime ,Boolean iswifi) {


SimpleDateFormat df = new SimpleDateFormat("MM月dd日 HH:mm:ss");


try {
Date now = df.parse(takeTime);
Date old = df.parse(presentime);
long l = old.getTime() - now.getTime() ;
long lastwifi = 0l ;
long wifitotal ;


if(iswifi) {
try {
lastwifi = Settings.System.getLong(context.getContentResolver(), "wifitotal");
Settings.System.putLong(context.getContentResolver(),"wifitotal", l);
} catch (SettingNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wifitotal = l+lastwifi ;
Settings.System.putLong(context.getContentResolver(),"wifitotal", wifitotal);

return DateUtils.formatElapsedTime(wifitotal/ 1000);
}else {
return DateUtils.formatElapsedTime(l/ 1000);
}


} catch (ParseException e) {
e.printStackTrace();


}
return "";
}


public List<Map<String, Object>> getData(Context context) {
//List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map = new HashMap<String, Object>();
map.put("iv_type", "wifi使用总时长:");
map.put("content",Settings.System.getString(context.getContentResolver(),"lasttime"));//上次使用时间
map.put("iv_sos", Settings.System.getString(context.getContentResolver(),"wifitime"));//wifi总共用时
list.add(map);


Log.i(TAG, "225    list= "+list);//


return list;
}


public List<Map<String, Object>> getBatteryData(Context context) {
String batterylast = Settings.System.getString(context.getContentResolver(),"Batterylasttime");
Map<String, Object> map = new HashMap<String, Object>();
map.put("iv_type", "开机电量:");
map.put("content", Settings.System.getInt(context.getContentResolver(),"BIRD_BATTERY", 100)+"%");//开机电量
map.put("iv_sos", computingTime(context ,batterylast,getCurrent(),false)/*updateBatteryStats()*/);//获取开机距现在所用时间
list.add(map);
Log.i(TAG, "236    list= "+list);
return list;
}
private String updateBatteryStats() {
//系统从开机距离当前时间的相差
long uptime = SystemClock.elapsedRealtime();
return DateUtils.formatElapsedTime(uptime / 1000);
}
public String  getCurrent() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());


return simpleDateFormat.format(date);


}
public String  getwifilast() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("a hh:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());


return simpleDateFormat.format(date);


}

}

第三步 获取各个app 使用时间 

public class UsageStatsAdapter extends BaseAdapter {
    // Constants defining order for display order
private static final String TAG = "UsageStatsAdapter";
   private static final boolean localLOGV = false;
   private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
   private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
   private static final int _DISPLAY_ORDER_APP_NAME = 2;
   private UsageStatsManager mUsageStatsManager;
   private LayoutInflater mInflater;
   long begintime = 0l ;
   private PackageManager mPm;
   private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
   private LastTimeUsedComparator mLastTimeUsedComparator = new LastTimeUsedComparator();
   private UsageTimeComparator mUsageTimeComparator = new UsageTimeComparator();
   private AppNameComparator mAppLabelComparator;
   private final ArrayMap<String, String> mAppLabelMap = new ArrayMap<>();
   private final ArrayList<UsageStats> mPackageStats = new ArrayList<>();
   private Context context;
   String batterylast = "";
   public  UsageStatsAdapter(Context context ) {
   
  this.context = context;
  mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
       mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       mPm = context.getPackageManager();
       Calendar cal = Calendar.getInstance();
       cal.add(Calendar.DAY_OF_YEAR, -5);//设置中默认开始时间
  batterylast = Settings.System.getString(context.getContentResolver(),"Batterylasttime");
    SimpleDateFormat df = new SimpleDateFormat("MM月dd日 HH:mm:ss");
   
    try {
    Date begin = df.parse(batterylast);//wanchengguo
    begintime = begin.getTime();
    Log.i("WifiReceiver", "cal.getTimeInMillis()="+cal.getTimeInMillis()+"/n"+"begin="+begin.getTime());
} catch (Exception e) {
// TODO: handle exception
}
      


       final List<UsageStats> stats =
               mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
              begintime/*cal.getTimeInMillis()*/, System.currentTimeMillis());
       if (stats == null) {
           return;
       }


       ArrayMap<String, UsageStats> map = new ArrayMap<>();
       final int statCount = stats.size();
       for (int i = 0; i < statCount; i++) {
           final android.app.usage.UsageStats pkgStats = stats.get(i);


           // load application labels for each application
           try {
               ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
               String label = appInfo.loadLabel(mPm).toString();
               mAppLabelMap.put(pkgStats.getPackageName(), label);


               UsageStats existingStats =
                       map.get(pkgStats.getPackageName());
               if (existingStats == null) {
                   map.put(pkgStats.getPackageName(), pkgStats);
               } else {
                   existingStats.add(pkgStats);
               }


           } catch (NameNotFoundException e) {
               // This package may be gone.
           }
       }
       mPackageStats.addAll(map.values());


       // Sort list
       mAppLabelComparator = new AppNameComparator(mAppLabelMap);
       sortList();
   }


   @Override
   public int getCount() {
       return mPackageStats.size();
   }


   @Override
   public Object getItem(int position) {
       return mPackageStats.get(position);
   }


   @Override
   public long getItemId(int position) {
       return position;
   }


   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
       // A ViewHolder keeps references to children views to avoid unneccessary calls
       // to findViewById() on each row.
       AppViewHolder holder;


       // When convertView is not null, we can reuse it directly, there is no need
       // to reinflate it. We only inflate a new View when the convertView supplied
       // by ListView is null.
       if (convertView == null) {
           convertView = mInflater.inflate(R.layout.usage_stats_item, null);


           // Creates a ViewHolder and store references to the two children views
           // we want to bind data to.
           holder = new AppViewHolder();
           holder.pkgName = (TextView) convertView.findViewById(R.id.package_name);
           holder.lastTimeUsed = (TextView) convertView.findViewById(R.id.last_time_used);
           holder.usageTime = (TextView) convertView.findViewById(R.id.usage_time);
           convertView.setTag(holder);
       } else {
           // Get the ViewHolder back to get fast access to the TextView
           // and the ImageView.
           holder = (AppViewHolder) convertView.getTag();
       }


       // Bind the data efficiently with the holder
       String totaltime = computingTime(batterylast,getCurrent());
       Log.i("WifiReceiver", "totaltime="+totaltime);
       if(position==0) {
      holder.pkgName.setText("开机电量");
      
           holder.lastTimeUsed.setText(Settings.System.getInt(context.getContentResolver(),"BIRD_BATTERY", 100)+"%");
           holder.usageTime.setText(totaltime); 
       }else  if(position==1) {
      holder.pkgName.setText("wifi使用总时长");
           holder.lastTimeUsed.setText(Settings.System.getString(context.getContentResolver(),"lasttime"));
           holder.usageTime.setText(Settings.System.getString(context.getContentResolver(),"wifitime")); 
       }else {
       
       UsageStats pkgStats = mPackageStats.get(position);
       if (pkgStats != null) {
           String label = mAppLabelMap.get(pkgStats.getPackageName());
           holder.pkgName.setText(label);
           holder.lastTimeUsed.setText(DateUtils.formatSameDayTime(pkgStats.getLastTimeUsed(),
                   System.currentTimeMillis(), DateFormat.MEDIUM, DateFormat.MEDIUM));
           holder.usageTime.setText(
                   DateUtils.formatElapsedTime(pkgStats.getTotalTimeInForeground() / 1000));
       } else {
           Log.w(TAG, "No usage stats info for package:" + position);
       }
       }
       return convertView;
   }


   void sortList(int sortOrder) {
       if (mDisplayOrder == sortOrder) {
           // do nothing
           return;
       }
       mDisplayOrder= sortOrder;
       sortList();
   }
   private String updateBatteryStats() {
//系统从开机距离当前时间的相差
long uptime = SystemClock.elapsedRealtime();
return DateUtils.formatElapsedTime(uptime / 1000);
}
   private void sortList() {
       if (mDisplayOrder == _DISPLAY_ORDER_USAGE_TIME) {
           if (localLOGV) Log.i(TAG, "Sorting by usage time");
           Collections.sort(mPackageStats, mUsageTimeComparator);
       } else if (mDisplayOrder == _DISPLAY_ORDER_LAST_TIME_USED) {
           if (localLOGV) Log.i(TAG, "Sorting by last time used");
           Collections.sort(mPackageStats, mLastTimeUsedComparator);
       } else if (mDisplayOrder == _DISPLAY_ORDER_APP_NAME) {
           if (localLOGV) Log.i(TAG, "Sorting by application name");
           Collections.sort(mPackageStats, mAppLabelComparator);
       }
       notifyDataSetChanged();
   }
   public static class AppNameComparator implements Comparator<UsageStats> {
       private Map<String, String> mAppLabelList;


       AppNameComparator(Map<String, String> appList) {
           mAppLabelList = appList;
       }


       @Override
       public final int compare(UsageStats a, UsageStats b) {
           String alabel = mAppLabelList.get(a.getPackageName());
           String blabel = mAppLabelList.get(b.getPackageName());
           return alabel.compareTo(blabel);
       }
   }


   public static class LastTimeUsedComparator implements Comparator<UsageStats> {
       @Override
       public final int compare(UsageStats a, UsageStats b) {
           // return by descending order
           return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
       }
   }


   public static class UsageTimeComparator implements Comparator<UsageStats> {
       @Override
       public final int compare(UsageStats a, UsageStats b) {
           return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
       }
   }


   // View Holder used when displaying views
   static class AppViewHolder {
       TextView pkgName;
       TextView lastTimeUsed;
       TextView usageTime;
   }
   /**
* 计算两个时间差
*
* @param oldTime 开始时间
* @param nowTime 结束时间
* @return
*/
   
   
   public String computingTime(String takeTime, String presentime ) {


SimpleDateFormat df = new SimpleDateFormat("MM月dd日 HH:mm:ss");


try {
Date now = df.parse(takeTime);
Date old = df.parse(presentime);
long l = old.getTime() - now.getTime() ;
long lastwifi = 0l ;
long wifitotal ;



return DateUtils.formatElapsedTime(l/ 1000);



} catch (ParseException e) {
e.printStackTrace();


}
return "";
}
   public String  getCurrent() {

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());


return simpleDateFormat.format(date);


}

}

第四步别忘了注册广播WifiReceiver

<!--增加开机电量 wifi wifi热点使用时长 监测 begin-->
  <receiver android:name="com.negative.screen.widget.WifiReceiver" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="android.NET.wifi.RSSI_CHANGED"/>
                <action android:name="android.net.wifi.STATE_CHANGE"/>
                <action android:name="android.net.wifi.WIFI_AP_STATE_CHANGED"/>
                <action android:name="android.Net.wifi.WIFI_STATE_CHANGED"/>
                 <action android:name="android.Net.wifi.WIFI_STATE_CHANGED_ACTION"/>
                <action android:name="android.intent.action.BOOT_COMPLETED" />  
  
             <category android:name="android.intent.category.HOME" /> 
            </intent-filter>
        </receiver>   

         <!-- 增加开机电量 wifi wifi热点使用时长 监测 end-->


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值