I can't update the widget when is in charging state. The battery level stay the same. What is wrong in my code?
public class BatteryStatusWidgetActivity extends AppWidgetProvider {
/** Called when the activity is first created. */
private String batteryLevel = "init";
private String temperatura = "init";
private int widgetImageFrame = R.drawable.full;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
context.getApplicationContext().registerReceiver(this,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
updateView(context);
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().contentEquals(
"com.sec.android.widgetapp.APPWIDGET_RESIZE")
|| intent.getAction().equals(
"android.appwidget.action.APPWIDGET_UPDATE_OPTIONS")) {
} else {
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
level = (rawlevel * 100) / scale;
batteryLevel = level + "%";
// temperatura
int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,
-1) / 10;
temperatura = temperature + "°C";
widgetImageFrame = R.drawable.full;
updateView(context);
}
super.onReceive(context, intent);
}
public void updateView(Context context) {
RemoteViews thisViews = new RemoteViews(context.getApplicationContext()
.getPackageName(), R.layout.widget_layout);
thisViews.setTextViewText(R.id.widget_text, batteryLevel + " | "
+ temperatura);
thisViews.setImageViewResource(R.id.imageView1, widgetImageFrame);
ComponentName thisWidget = new ComponentName(context,
BatteryStatusWidgetActivity.class);
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget,
thisViews);
}
}
This is the main of widget
<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="#layout/widget_layout" android:minWidth="40dp" android:minHeight="40dp" android:updatePeriodMillis="3000" />
So what is the problem? android:updatePeriodMillis="3000"?
The updatePeriodMillis attribute defines how often the App Widget framework should request an update from the AppWidgetProvider by calling the onUpdate() callback method.
from http://developer.android.com/guide/topics/appwidgets/index.html#MetaData
Related
I have a clock widget that updates every minute. It renders a bitmap and replaces an imageview. This is to use a custom font in a widget. Below I showed the important pieces of my code. My problem is that the widget is there, but nothing shows up. I can still tap the widget to bring up the settings, so I know it's there. It's like the service update isn't working correctly in Kitkat but it does in Lollipop. Any suggestions?
public class DigitalClockWidget_2x1 extends AppWidgetProvider {
public RemoteViews mRemoteViews;
static String APP_SETTINGS = "8BitSettings";
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.startService(new Intent(UpdateTimeService.UPDATE_TIME));
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent LaunchIntent = getLaunchIntent(context);
PendingIntent clickPendIntent = PendingIntent.getActivity(context, 0, LaunchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mRemoteViews.setOnClickPendingIntent(R.id.widget_root, clickPendIntent);
ComponentName componentName = new ComponentName(context.getPackageName(),DigitalClockWidget_2x1.class.getName());
appWidgetManager.updateAppWidget(componentName, mRemoteViews);
context.startService(new Intent(UpdateTimeService.UPDATE_TIME));
}
public static Intent getLaunchIntent(Context context){
SharedPreferences clockSettings = context.getSharedPreferences("ClockSettings", 0);
String launchString = clockSettings.getString("tappedAction", APP_SETTINGS);
if(launchString.compareTo(APP_SETTINGS) == 0){
return new Intent(context, SettingsPage.class);
}
return context.getPackageManager().getLaunchIntentForPackage(launchString);
}
public static final class UpdateTimeService extends Service {
static final String UPDATE_TIME = "org.penguinproductions.eight_bit_clock.action.UPDATE_TIME_2x1";
RemoteViews mRemoteViews;
private Calendar mCalendar;
private final static IntentFilter mIntentFilter = new IntentFilter();
int textColor = 0;
boolean tweentyfourHour = false;
SharedPreferences clockSettings;
String APP_SETTINGS = "8BitSettings";
static {
mIntentFilter.addAction(Intent.ACTION_TIME_TICK);
mIntentFilter.addAction(Intent.ACTION_TIME_CHANGED);
mIntentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
}
#Override
public void onCreate() {
super.onCreate();
mCalendar = Calendar.getInstance();
registerReceiver(mTimeChangedReceiver, mIntentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mTimeChangedReceiver);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent != null) {
if (UPDATE_TIME.equals(intent.getAction())) {
updateTime();
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private final BroadcastReceiver mTimeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateTime();
}
};
private void updateTime() {
mCalendar.setTimeInMillis(System.currentTimeMillis());
mRemoteViews = new RemoteViews(getPackageName(), R.layout.widget);
String date = DateFormat.format(getString(R.string.date_format), mCalendar).toString();
mRemoteViews.setImageViewBitmap(R.id.imageView_txt, buildUpdate(getTodaysTime(), mCalendar.get(Calendar.AM_PM), date));
ComponentName mComponentName = new ComponentName(this, DigitalClockWidget_2x1.class);
AppWidgetManager mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetManager.updateAppWidget(mComponentName, mRemoteViews);
Intent LaunchIntent = getLaunchIntent(getBaseContext());
PendingIntent clickPendIntent = PendingIntent.getActivity(getBaseContext(), 0, LaunchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mRemoteViews.setOnClickPendingIntent(R.id.widget_root, clickPendIntent);
mAppWidgetManager = AppWidgetManager.getInstance(getBaseContext());
mAppWidgetManager.updateAppWidget(mComponentName, mRemoteViews);
}
}
EDIT:
The issue seems to have to do with the Bitmap rendering. I replaced the imageview with a textview and it worked. So the Bitmap isn't displaying in KitKat, but it does in Lollipop
public Bitmap buildUpdate(String time, int AMPM, String date) {
Log.v("Penguin", "Building time string:" + time);
clockSettings = this.getSharedPreferences("ClockSettings", 0);
boolean showDate = clockSettings.getBoolean("showDate", true);
boolean showampm = clockSettings.getBoolean("ampm", true);
boolean leading0 = clockSettings.getBoolean("leading0", true);
textColor = clockSettings.getInt("clockColor", Color.WHITE);
int dateColor = clockSettings.getInt("dateColor", Color.WHITE);
Bitmap myBitmap = Bitmap.createBitmap(2500, 1100, Bitmap.Config.ARGB_8888);
int fontSize = 425;
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Typeface clock = Typeface.createFromAsset(this.getAssets(), "fonts/PressStart2P.ttf");
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(clock);
paint.setStyle(Paint.Style.FILL);
paint.setColor(textColor);
paint.setTextSize(fontSize);
paint.setTextAlign(Paint.Align.CENTER);
myCanvas.drawText(time, myBitmap.getWidth() / 2, fontSize+200, paint);
paint.setTextSize(100);
if(showampm) {
// alert("AMPM");
String ampm = "AM";
if (AMPM == 1) ampm = "PM";
myCanvas.drawText(ampm, (myBitmap.getWidth() / 2) + ((time.length() * fontSize) / 2) + 100, 300, paint);
}
paint.setTextSize(125);
if(showDate) {
paint.setColor(dateColor);
myCanvas.drawText(date, myBitmap.getWidth() / 2, (myBitmap.getHeight() / 2 + 400), paint);
}
return myBitmap;
}
So the issue was that the size limit for my older phone running KitKat only allows for texture sizes no bigger than 2048x2048 pixels. My bitmap was 2500x1100, so scaling it down has fixed the issue
My assumption is that I just do not fully understand widgets yet. Hopefully one of you guru's can see where my logic/thinking is flawed.
Ultimately what happens with my widget is that it eventually becomes unresponsive at very random intervals (usually > 5 hours).
My investigation so far has led me to believe that it's potentially a result of the OS running low on memory and my widget being recreated?
If that's the case, I would have thought that the OnUpdate() method would handle this but potentially I'm wrong here.
I have read pretty much every thread on here regarding widget unresponsiveness. The only one that showed promise for me was this one:
Android Homescreen Widget becomes Unresponsive
but I'm not using a service and not sure I need to.
The goal of the widget is to first check if the user has created a profile. This is done by checking for the existence of a local db along with a user record. If neither of these exist, the widget should display a "Get Started" image (which it does successfully).
Once the user taps on this image, they are launched into a profile creation wizard. Once the profile is created, the widget is updated from the app to display an image along with some caloric intake information.
There are three clickable items on the widget. The image and the two textviews. Each respectively launching a different activity in my app.
Here is the widget class:
public class bbi_widget extends AppWidgetProvider {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
private static String week6Path = "";
public static RemoteViews getWidgetRemoteViews(Context context) {
Intent calorieCrushIntent = new Intent(context, calorie_crush.class);
Intent dashBoardIntent = new Intent(context, DashboardActivity.class);
PendingIntent calorieCrushPendingIntent = PendingIntent.getActivity(
context, 0, calorieCrushIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent dashboardPendingIntent = PendingIntent.getActivity(
context, 0, dashBoardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews appWidgetViews = new RemoteViews(context.getPackageName(),
R.layout.initial_widget_layout);
appWidgetViews.setOnClickPendingIntent(R.id.surp_def_widgettextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.calTextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, dashboardPendingIntent);
return appWidgetViews;
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
BBIDatabase db = new BBIDatabase(context);
db.openToRead();
boolean doesTableExist = db.doesTableExist(BBIDatabase.BBI_USER_TABLE);
db.close();
boolean doesUserExist = false;
if (doesTableExist){
db.openToRead();
doesUserExist = db.doesUserExist();
db.close();
}
if (!doesTableExist || !doesUserExist){
Intent getStartedIntent = new Intent(context, GettingStartedWizardActivity.class);
PendingIntent getStartedPendingIntent = PendingIntent.getActivity(
context, 0, getStartedIntent, PendingIntent.FLAG_UPDATE_CURRENT);
for (int index = 0; index < appWidgetIds.length; index++) {
int appWidgetId = appWidgetIds[index];
RemoteViews appWidgetViews = getWidgetRemoteViews(context);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, getStartedPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, appWidgetViews);
}
} else {
db.openToRead();
String curPath = db.GetSixWeekPath();
Bitmap sixWeekBmp = null;
if (week6Path != curPath && curPath != null && week6Path != null) {
week6Path = db.GetSixWeekPath();
sixWeekBmp = BitmapFactory.decodeFile(week6Path);
}
db.close();
db.openToRead();
int totalCalsToday = db.GetTodaysCalorieIntakeForWidget();
int bmrWithAct = db.GetBMRPlusActivity();
int additionalCalsCrushed = db.GetTodaysCaloriesBurnedForWidget();
int surp = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (surp < 0)
surp = 0;
int def = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (def > 0)
def = 0;
db.close();
for (int index = 0; index < appWidgetIds.length; index++) {
int appWidgetId = appWidgetIds[index];
RemoteViews appWidgetViews = getWidgetRemoteViews(context);
appWidgetViews.setViewVisibility(R.id.calTextView, View.VISIBLE);
appWidgetViews.setViewVisibility(R.id.surp_def_widgettextView, View.VISIBLE);
appWidgetViews.setTextViewText(R.id.calTextView, "Calorie intake: " + String.valueOf(totalCalsToday));
if (surp > 0) {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "SURPLUS " + String.valueOf(surp));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.surplus_ball_color));
} else {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "DEFICIT " + String.valueOf(def));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.calorie_crush_ball));
}
appWidgetViews.setImageViewBitmap(R.id.widget_after_picture, sixWeekBmp);
Intent calorieCrushIntent = new Intent(context, calorie_crush.class);
Intent dashBoardIntent = new Intent(context, DashboardActivity.class);
PendingIntent calorieCrushPendingIntent = PendingIntent.getActivity(
context, 0, calorieCrushIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent dashboardPendingIntent = PendingIntent.getActivity(
context, 0, dashBoardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
appWidgetViews.setOnClickPendingIntent(R.id.surp_def_widgettextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.calTextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, dashboardPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, appWidgetViews);
}
}
}
}
From my app, I do update these values in the widget using remoteViews.
Here is the helper class in my app:
public class WidgetHelper {
public static void UpdateCalorieIntake(int newValue, Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.initial_widget_layout);
ComponentName thisWidget = new ComponentName(context, bbi_widget.class);
remoteViews.setTextViewText(R.id.calTextView, "Calories in " + String.valueOf(newValue));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
public static void UpdateWidgetSurplus(int newValue, Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.initial_widget_layout);
ComponentName thisWidget = new ComponentName(context, bbi_widget.class);
if (newValue > 0) {
remoteViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric Surplus " + String.valueOf(newValue));
remoteViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.surplus_ball_color));
} else {
remoteViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric Deficit " + String.valueOf(newValue));
remoteViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.calorie_crush_ball));
}
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
private static String week6Path = "";
public static void UpdateAll(Context context) {
BBIDatabase db = new BBIDatabase(context);
db.openToRead();
String curPath = db.GetSixWeekPath();
Bitmap sixWeekBmp = null;
if (week6Path != curPath && curPath != null && week6Path != null) {
week6Path = db.GetSixWeekPath();
sixWeekBmp = BitmapFactory.decodeFile(week6Path);
}
db.close();
db.openToRead();
int totalCalsToday = db.GetTodaysCalorieIntakeForWidget();
int bmrWithAct = db.GetBMRPlusActivity();
int additionalCalsCrushed = db.GetTodaysCaloriesBurnedForWidget();
int surp = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (surp < 0)
surp = 0;
int def = totalCalsToday - (bmrWithAct + additionalCalsCrushed);
if (def > 0)
def = 0;
db.close();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews appWidgetViews = new RemoteViews(context.getPackageName(), R.layout.initial_widget_layout);
ComponentName thisWidget = new ComponentName(context, bbi_widget.class);
appWidgetViews.setTextViewText(R.id.calTextView, "Calorie intake: " + String.valueOf(totalCalsToday));
if (surp > 0) {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric surplus " + String.valueOf(surp));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.surplus_ball_color));
} else {
appWidgetViews.setTextViewText(R.id.surp_def_widgettextView, "Caloric deficit " + String.valueOf(def));
appWidgetViews.setTextColor(R.id.surp_def_widgettextView, context.getResources().getColor(R.color.calorie_crush_ball));
}
appWidgetViews.setImageViewBitmap(R.id.widget_after_picture, sixWeekBmp);
Intent calorieCrushIntent = new Intent(context, calorie_crush.class);
Intent dashBoardIntent = new Intent(context, DashboardActivity.class);
PendingIntent calorieCrushPendingIntent = PendingIntent.getActivity(
context, 0, calorieCrushIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent dashboardPendingIntent = PendingIntent.getActivity(
context, 0, dashBoardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
appWidgetViews.setOnClickPendingIntent(R.id.surp_def_widgettextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.calTextView, calorieCrushPendingIntent);
appWidgetViews.setOnClickPendingIntent(R.id.widget_after_picture, dashboardPendingIntent);
appWidgetManager.updateAppWidget(thisWidget, appWidgetViews);
}
}
Provider infor:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dp"
android:minHeight="294dp"
android:previewImage="#drawable/bbi_icon"
android:initialLayout="#layout/initial_widget_layout"
>
</appwidget-provider>
I found this code to create a battery widget:
public class BatteryStatusWidgetActivity extends AppWidgetProvider {
/** Called when the activity is first created. */
private String batteryLevel = "init";
private int widgetImageFrame = R.drawable.widget_batt_frame01;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
updateView(context);
}
#Override
public void onReceive(Context context, Intent intent) {
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = 65;
level = (rawlevel * 100) / scale;
String batteryLevel = level + "%";
widgetImageFrame = R.drawable.widget_batt_frame01;
updateView(context);
super.onReceive(context, intent);
}
public void updateView(Context context) {
RemoteViews thisViews = new RemoteViews(context.getApplicationContext().getPackageName(), R.layout.widget_layout);
thisViews.setTextViewText(R.id.widget_text, batteryLevel);
thisViews.setImageViewResource(R.id.imageView1, widgetImageFrame);
ComponentName thisWidget = new ComponentName(context, BatteryStatusWidgetActivity.class);
AppWidgetManager.getInstance(context).updateAppWidget(thisWidget, thisViews);
}
This will display in the widget only the number of battery level. I mean "65" and i want display "65%". But if i try to write something like batteryLevel = Integer.toString(level+"%"); i get error.. How can i do it?
int level = 65;
String batteryLevel = level + "%";
Try this it will work
int level= 65;
String batterylevel = String.valueOf(level)+"%";
just replace your code in onReceive() to the following,
#Override
public void onReceive(Context context, Intent intent) {
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
level = (rawlevel * 100) / scale;
batteryLevel = level+"%";
widgetImageFrame = R.drawable.widget_batt_frame01;
updateView(context);
super.onReceive(context, intent);
}
The basic reason you get an error for Integer.toString(level+"%") is Integer.toString() method used here accepts an int value but not a String value. level+"%" is a String value
Change it to this:
int level = -1
level = (rawlevel * 100) / scale;
String batteryLevel = level + "%";
I'm making a widget and i know some of my code such as the broadcastReceiver is wrong at the moment but it wont even update to hardcoded setTextViewText.
My problem is I've no idea why this happens and my widget just wont update.
Here's my code i hope someone can figure out where ive gone wrong:
public class Widget extends AppWidgetProvider {
RemoteViews views;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int N = appWidgetIds.length;
views = new RemoteViews(context.getPackageName(), R.layout.widget);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
IntentFilter batteryLevelFliter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
context.registerReceiver(batteryChangedReceiver, batteryLevelFliter);
String alarm = Settings.System.getString(context.getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
views.setTextViewText(R.id.tvAlarm, alarm);
views.setTextViewText(R.id.tvNextAlarm, "qwertyuiop");
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int rawLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawLevel >= 0 && scale > 0) {
level = (rawLevel * 100) / scale;
}
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean charging = status == BatteryManager.BATTERY_STATUS_CHARGING;
if (charging) {
views.setTextViewText(R.id.tvBattery, "Charging: " + level + "%");
if (level == 100) {
views.setTextViewText(R.id.tvBattery, "Battery Full");
}
} else {
views.setTextViewText(R.id.tvBattery, "Battery: " + level + "%");
}
}
};
}
AppWidgetProvider extends android.content.BroadcastReceiver, so you cannot register new BroadcastReceiver to the your AppWidget's context. In your code, you will not receive battery event from your BroadcastReceiver. Refer these previous questions. :)
Android Broadcast Receiver in Widget
Register BroadcastReceiver to Widget (Difference of Context object)
I tried solving my problem using this link
update - I figured out that there is something wrong with the setter of the pending intent- every time I click on the imageview- the intent sends the extre details of the last defined widget-
meaning that the other pending intents that where defined on the pre-added widgets were run-over by the newer widgets
I have an app widget that shows a picture chosen by the user.(many widgets- many pictures)
my problem is: no matter which widget on screen I press - only the last added widget gets updated:
here is my code
My Widget xml provider Code
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="#layout/widget_Test"
android:minHeight="146dip"
android:minWidth="146dip"
android:updatePeriodMillis="0" />
My Manifest xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.BIND_REMOTEVIEWS" >
</uses-permission>
<application
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:name=".Activities.WidgetConfig"
android:screenOrientation="portrait" >
<!-- prbbly delete this line -->
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</activity>
<!-- Test Widget -->
<receiver
android:name=".Simple.Widget"
android:label="#string/app_widget_Test" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_Test_provider" />
</receiver>
<service android:name=".Simple.Widget$TestWidgetService" />
</application>
</manifest>
Widget provider
public class Widget extends AppWidgetProvider
{
public static String PREFENCES_WIDGET_CONFIGURE = "ActionConfigureWidget";
public static int[] widgets;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds)
{
Intent svcIntent = new Intent(context, TESTWidgetService.class);
widgets = appWidgetIds;
context.startService(svcIntent);
}
public static class TESTWidgetService extends Service
{
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
// Update the widget
RemoteViews remoteView = buildRemoteView(this);
// Push update to homescreen
Mngr.getInstance().pushUpdate(remoteView,
getApplicationContext(), Widget.class);
// No more updates so stop the service and free resources
stopSelf();
}
public RemoteViews buildRemoteView(Context context)
{
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_TEST);
if (widgets != null)
{
int length = widgets.length;
for (int i = 0; i < length; i++)
{
Intent configIntent = new Intent(context,
WidgetConfig.class);
configIntent.setAction(Widget.PREFENCES_WIDGET_CONFIGURE);
String number = AppWidgetManager.EXTRA_APPWIDGET_ID
+ "number";
configIntent.putExtra(number, length);
String widgetID = AppWidgetManager.EXTRA_APPWIDGET_ID + i;
int id = widgets[i];
configIntent.putExtra(widgetID, id);
PendingIntent runTESTPendingIntent = PendingIntent
.getActivity(context, 0, configIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.TESTWidgetImage,
runTESTPendingIntent);
Mngr controller = Mngr.getInstance();
controller.updateTESTWidget(context, remoteViews);
}
}
return remoteViews;
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
int oldOrientation = this.getResources().getConfiguration().orientation;
if (newConfig.orientation != oldOrientation)
{
// Update the widget
RemoteViews remoteView = buildRemoteView(this);
// Push update to homescreen
Mngr.getInstance().pushUpdate(remoteView,
getApplicationContext(), Widget.class);
}
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
}
}
my config activity
public class WidgetConfig extends ListActivity // implements
{
private Bundle m_extras;
private ArrayList<Test> m_tests = null;
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
ImageAdapter m_adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagelist);
Resources res = getResources();
Mngr mngr = Mngr.getInstance();
mngr.setResources(res);
Context ctx = getApplicationContext();
mngr.setContext(ctx);
getTests();
m_adapter = new ImageAdapter(ctx, R.layout.row, m_tests);
ImageDownloader.Mode mode = ImageDownloader.Mode.CORRECT;
m_adapter.getImageDownloader().setMode(mode);
setListAdapter(m_adapter);
Intent intent = getIntent();
m_extras = intent.getExtras();
}
private void getTests()
{
m_tests = new ArrayList<Test>();
Resources res = getResources();
String[] TestNames = res.getStringArray(R.array.fav_Test_array);
TypedArray imgs = getResources().obtainTypedArray(
R.array.fav_Test_integer);
for (int i = 0; i < TestNames.length; i++)
{
Test o1 = new Test();
String TestName = TestNames[i];
int resID = imgs.getResourceId(i, -1);
o1.setTestName(TestName);
o1.setIMGID(resID);
m_tests.add(o1);
}
imgs.recycle();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
ListAdapter adapt = l.getAdapter();
Object obj = adapt.getItem(position);
if (obj != null)
{
Mngr mngr = Mngr.getInstance();
Context context = getApplicationContext();
String key = context.getString(R.string.TestWidget_string) + "_"
+ AppWidgetManager.EXTRA_APPWIDGET_ID;
Test Test = (Test) obj;
String val = Test.getIMGID().toString();
mngr.putString(context, key, val);
updateWidget();
}
super.onListItemClick(l, v, position, id);
}
private void updateWidget()
{
Context ctx = getApplicationContext();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(ctx);
setResult(RESULT_CANCELED);
if (m_extras != null)
{
Intent resultValue = new Intent();
int numberOfWidgets = m_extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID + "number",
AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < numberOfWidgets; i++)
{
String stringID = AppWidgetManager.EXTRA_APPWIDGET_ID + i;
mAppWidgetId = m_extras.getInt(stringID,
AppWidgetManager.INVALID_APPWIDGET_ID);
/*************************************************************/
/*I Don't really know if I am using this piece of code right */
Uri data = Uri.withAppendedPath(Uri.parse("ABCD"
+ "://widget/id/"), String.valueOf(mAppWidgetId));
resultValue.setData(data);
/*************************************************************/
RemoteViews views = new RemoteViews(ctx.getPackageName(),
R.layout.widget_Test);
Mngr.getInstance().updateTestWidget(ctx, views);
appWidgetManager.updateAppWidget(mAppWidgetId, views);
resultValue.putExtra(stringID, mAppWidgetId);
}
setResult(RESULT_OK, resultValue);
finish();
}
}
}
My Mngr code
public void updateTestWidget(Context context, RemoteViews remoteViews)
{
String key = context.getString(R.string.TestWidget_string) + "_"
+ AppWidgetManager.EXTRA_APPWIDGET_ID;
String s = getString(context, key, "");
if (s != null && s.equals("") == false)
{
int resID = Integer.valueOf(s);
remoteViews.setImageViewResource(R.id.TestWidgetImage, resID);
}
}
public void pushUpdate(RemoteViews remoteView, Context ctx, Class<?> cls)
{
ComponentName myWidget = new ComponentName(ctx, cls);
AppWidgetManager manager = AppWidgetManager.getInstance(ctx);
manager.updateAppWidget(myWidget, remoteView);
}
The problem isn't your configActivity, the problem is in your widgetProvider. I had the same problem as you did but solved using the link you specified. You need to set the "hacked" intent on your configIntent in buildRemoteView.
I had the same problem when I tested my application on emulator of 2.2 or 2.3 version. On a real device everything should work fine. Moreover, in my case emulator 4.0 worked properly. In any case I recommend you to test it on a real device.