I'm new to Android Studio and Java and I'm trying to display a dynamic battery percentage on multiple activities, but it is only showing on the main screen. I am also trying to do the same thing with displaying time. I am trying to get it work with my second activity (insulin.xml) with a TextView with an ID of lblBatteryInsulin.
mainActivity.Java
package com.example.insulinpump;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.view.View;
import android.os.BatteryManager;
import android.content.BroadcastReceiver;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends WearableActivity {
private static final String TAG = "MainActivity.java";
// insulin calculations
int insulin = 0;
int glucose = -1;
// insulin.xml, activity_main.xml:
TextView txtGlucose, lblGlucose;
Button btnBasal, btnBolus;
private TextView txtTime;
private TextView battery; //Battery
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// insulin.xml, activity_main.xml:
lblGlucose = (TextView) findViewById(R.id.lblGlucoseInsulin);
// Enables Always-on
setAmbientEnabled();
txtTime = findViewById(R.id.lblTimeLog);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
String dateTime = simpleDateFormat.format(calendar.getTime());
txtTime.setText(dateTime);
battery =(TextView)findViewById(R.id.lblBatteryPercent);
this.registerReceiver(this.batterylevelReciever, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
// Battery Percentage
private BroadcastReceiver batterylevelReciever = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0 );
battery.setText(String.valueOf(level)+ "%");
}
};
// all xml:
// Display functions:
public void goHome(android.view.View View) {
setContentView(R.layout.activity_main);
}
public void insulinView(android.view.View View) {
setContentView(R.layout.insulin);
txtGlucose = (TextView) findViewById(R.id.lblGlucoseInsulin);
btnBasal = (Button) findViewById(R.id.btnBasal);
btnBolus = (Button) findViewById(R.id.btnBolus);
btnBasal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
calculate(true);
}
});
btnBolus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
calculate(false);
}
});
//Time
txtTime = findViewById(R.id.lblTimeLog);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
String dateTime = simpleDateFormat.format(calendar.getTime());
txtTime.setText(dateTime);
}