显示充电类型

时间:2018-02-21 17:21:40

标签: android battery batterylevel batterymanager

我的代码有4种不同的文本视图,显示4种不同的文本,前3种显示为真或假,最后一种显示电池的百分比

1电池充电
2电池UsbCharge
3.电池充电器 4.电池生活

我有电池寿命工作,但我不知道如何将前3个显示为真或假。以下是我的代码

主要活动

package com.example.a000339326.myapplication;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tv = (TextView) findViewById(R.id.TxtV1);
    TextView tv2 = (TextView) findViewById(R.id.TxtV2);
    TextView tv3 = (TextView) findViewById(R.id.TxtV3);
    TextView tv4 = (TextView) findViewById(R.id.TxtV4);


    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent intent = registerReceiver(null, intentFilter);
    Intent batteryStatus = registerReceiver(null, intentFilter);

    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
    float percent = (float) (level / scale) * 100;

    tv.setText("Battery Life " + String.valueOf(percent));
    tv2.setText("Battery Charge " + );
    tv3.setText("Battery usbCharge " + );
    tv4.setText("Battery acCharge " + );
    }
}

的Manifest.xml

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a000339326.myapplication">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/lab5"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

 </manifest>

接收者类

package com.example.a000339326.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;

 public class myReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
            status == BatteryManager.BATTERY_STATUS_FULL;

    int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
     }
}

0 个答案:

没有答案