I'm trying to get my widget to update when my battery percentage change. Iv'e solved for when i press the widget so it updates but that kind of ruins it for me. It updates by default every 30min. I don't want it to change after a period of time but when my battery goes down or if charge- going up. Also is it possible to change the color of a shape with code? I have a percentage ring I would like to change when battery is down by say 50% or so.
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;
import android.widget.RemoteViews;
public class Battery extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[]
appWidgetsIds) {
ComponentName newWidget = new ComponentName(context, BlueTooth.class);
int[] widgetId = appWidgetManager.getAppWidgetIds(newWidget);
String name = "My Phone";
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
assert batteryStatus != null;
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int batteryPct = level * 100 / scale;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.blue_tooth);
Log.w("Percentage", String.valueOf(batteryPct));
remoteViews.setTextViewText(R.id.percent, (batteryPct) + "%");
remoteViews.setTextViewText(R.id.update, name);
Intent intent = new Intent(context, BlueTooth.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetsIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.percent, pendingIntent);
remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadius="25dp"
android:thickness="3dp"
android:useLevel="false"
>
<gradient
android:endColor="#3CB371"
android:type="radial"
android:useLevel="false"
/>
</shape>