安卓开发显示手机当前电量和时间-大字版,适合家里老人使用

显示手机当前电量和时间-大字版,适合家里老人使用

1. MainActivity 代码:

public class MainActivity extends Activity {

    private TextView power;
    private TextView time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        power = findViewById(R.id.tv_power);

        Date date = new Date();
//        String currentTime = date.toLocaleString();

        time = findViewById(R.id.tv_time);

        //设置时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm E");
        String currentTime = dateFormat.format(date);
        time.setText("当前时间:"+currentTime);
        
		//实例化广播接收类
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        
            @Override
            public void onReceive(Context context, Intent intent) {
                if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){
                    int level = intent.getIntExtra("level", 0);
                    int scale = intent.getIntExtra("scale",100);
                    power.setText("当前剩余电量:"+(level*100/scale+"%"));
                }
            }
        };
        
        //设置过滤器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        
        //动态注册
        registerReceiver(broadcastReceiver, intentFilter);
    }
}

2. activity_main.xml 代码:


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_power"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="114dp"
        android:textColor="@color/teal_700"
        android:textSize="65dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_time" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="7dp"
        android:text="TextView"
        android:textSize="65dp"
       app:layout_constraintBottom_toTopOf="@+id/tv_power"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

androidx.constraintlayout.widget.ConstraintLayout>

3. 运行结果截图:
安卓开发显示手机当前电量和时间-大字版,适合家里老人使用_第1张图片

你可能感兴趣的:(安卓移动开发,android,studio,移动开发,android)