我正在开发Android Studio上的电池健康应用程序。我想知道如何通过播放音乐或视频、浏览网站或待机来计算剩余时间。我见过很多像这样的安卓应用,但看不到源代码。我希望看到用于计算播放音乐或视频的剩余时间等的示例代码。如果你之前开发过android电池健康应用,请分享你的知识。
发布于 2016-03-10 20:33:49
--计算剩余电池寿命的最简单和最容易的方法:
MainActivity.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView batteryPercent;
private void getBatteryPercentage() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (currentLevel >= 0 && scale > 0) {
level = (currentLevel * 100) / scale;
}
batteryPercent.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
batteryPercent = (TextView) this.findViewById(R.id.batteryLevel);
getBatteryPercentage();
}
}xml文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/batteryLevel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:textSize="20dip">
</TextView>
</RelativeLayout>发布于 2016-03-10 20:30:21
您无法准确猜测电池放电的剩余时间,因为可能存在不同的应用程序或服务消耗电池。
但是,您可以在广播接收器的帮助下,通过为操作Intent.ACTION_BATTERY_CHANGED注册接收器来获得电池续航时间。
通过在带有上述意图操作的BroadcastReceiver的onReceive()方法中使用下面的语句,您将获得当前可用的电池电量。但你不能估计剩余的时间,因为一些应用程序可能会消耗更多的电力。
battery_level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);发布于 2016-03-10 20:40:38
以下代码将帮助您计算电池电量
public int getBatteryLevel(Context context) {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
return level;
}https://stackoverflow.com/questions/35916446
复制相似问题