Introduction
I'm trying to make a widget for school as homework. It is done for Android SO and coded in Java. I'm pretty new to this so I had to read A LOT of documentation, specially from their main Website for Android Devs, I'm not that interested in Android developing so a quick and solid answer is more than welcome.
Problem
I'm sending a name and ID from a WidgetConfig class (an Activity) using an Intent to the widget. This data is supposed to be written on the TextView from the widget layout but for some reason it does not.
In this code below you may see my attempt, if you tested the program from the repository that I will provide you are going to see that it is not properly updated.
So my question is:
How I can manage to update my widget from data sent from an activity?
public class FerrixWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.ferrix_widget);
//views.setTextViewText(R.id.appwidget_text, widgetText);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
RemoteViews spm = new RemoteViews(context.getPackageName(), R.layout.ferrix_widget);
spm.setTextViewText(R.id.alumnoName, "plsupdate");
}
//This is called to update the App Widget at intervals defined by the updatePeriodMillis attribute
// in the AppWidgetProviderInfo.
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
//This is called when an instance the App Widget is created for the first time.
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
System.out.println("[INFO] FIRST INSTANCE CREATED");
}
//This is called when the last instance of your App Widget is deleted from the App Widget host.
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
//This is called for every broadcast and before each of the above callback methods.
#Override
public void onReceive(Context context, Intent intent) {
RemoteViews controles = new RemoteViews(context.getPackageName(), R.layout.ferrix_widget);
String alumnoName = intent.getStringExtra("Name"); //Gets the intent withthe key "Name"
System.out.println("[INFO] Key: Name gets result: " + alumnoName);
controles.setTextViewText(R.id.alumnoName, alumnoName);
controles.setTextViewText(R.id.claseName, "DAM2");
System.out.println("[INFO] Context: " + context);
System.out.println("[INFO] Received: " + intent.getAction().toString());
}
}
Full code at
https://gitlab.com/JonaFerre/ferrixwidget
My goal
I want that when you set tup the widget on your screen it pops up a config screen (it does that already), then you insert your name and class, this data is sent over to the widget (via Intent) so it gets written and shown alongside the time of the day and some other stuff (That I will add once I get this properly solved)
Notes:
IDE: Android Studio
Andriod: v15
You can easily fix this by updating your widget in widget's onReceive:
Just send a broadcast from configuration activity:
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("WidgetPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("msg_" + widgetId, nameInput.getText().toString()); //???
editor.commit();
//Actualizar el widget tras la config
System.out.println("[INFO] Getting instance of WidgetConfig");
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(WidgetConfig.this);
System.out.println("[INFO] Updating the widget");
FerrixWidget.updateAppWidget(WidgetConfig.this, appWidgetManager, widgetId);
//Devolver un buen OK
Intent resultado = new Intent();
resultado.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
//System.out.println("[CONFIG INFO] Name text is: " + nameInput.getText().toString());
resultado.putExtra("Name", nameInput.getText().toString());
resultado.setAction("myUpdate");
ComponentName componentName = new ComponentName(getApplicationContext(), FerrixWidget.class);
resultado.setComponent(componentName);
sendBroadcast(resultado);
setResult(RESULT_OK, getIntent());
finish();
System.out.println("[INFO] OK devuelto!");
}
});
and on widget's onReceive
public void onReceive(Context context, Intent intent) {
if(intent.getAction() != null && intent.getAction().equals("myUpdate")) {
RemoteViews controles = new RemoteViews(context.getPackageName(), R.layout.ferrix_widget);
String alumnoName = intent.getStringExtra("Name"); //Gets the intent withthe key "Name"
int id = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
System.out.println("[INFO] Key: Name gets result: " + alumnoName);
controles.setTextViewText(R.id.alumnoName, alumnoName);
controles.setTextViewText(R.id.claseName, "DAM2");
AppWidgetManager.getInstance(context).updateAppWidget(id, controles);
System.out.println("[INFO] Context: " + context);
System.out.println("[INFO] Received: " + intent.getAction().toString());
} else {
super.onReceive(context, intent);
}
}
But the better way is to save your data and widget's id in db/preference and just update on widget's side in onUpdate.
Please, just read official doc. There a lot of stuff that can helps you.
Related
I created a widget, which was working quite fine, and then I changed targetSDK from 23 to 26, due to the requirement from Google Play Developer Console.
After switching to Android SDK 26, my app widget is no more updating on the screen_on/User_present event. I can see that there are a bunch of changes in Android 26 for background running task due to (Background Execution Limits).
Following are my questions?
Q1- How can I update my app widget on every screen_on event, so that the user will see the right status on widget?
Q2- How can I update my app widget periodically after every 1 hour?
Following code I'm currently using.
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget);
String token = getToken();
getUUID();
getGatewayActivationStatus();
getEnvironment();
if (token != null) {
remoteViews.setViewVisibility(R.id.layoutBtn, View.VISIBLE);
AppWidgetIntentReceiver appWI = new AppWidgetIntentReceiver();
appWI.getMode(context);
} else {
remoteViews.setTextViewText(R.id.txt_mode, "Please sign into your App to see status.");
remoteViews.setViewVisibility(R.id.layoutBtn, View.INVISIBLE);
}
remoteViews.setOnClickPendingIntent(R.id.btn_refresh, buildButtonPendingIntent(context, _refresh));
remoteViews.setOnClickPendingIntent(R.id.txt_mode, buildButtonPendingIntent(context, _openApp));
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {
super.onEnabled(context);
}
#Override
public void onDisabled(Context context) {
super.onDisabled(context);
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);//add this line
AppWidgetIntentReceiver appWI = new AppWidgetIntentReceiver();
if (_standby.equals(intent.getAction()) || _home.equals(intent.getAction()) || _away.equals(intent.getAction()) || _refresh.equals(intent.getAction()) || _openApp.equals(intent.getAction())) {
appWI.handleClickEvent(context, intent, intent.getAction());
} else if (intent.getAction().equals("android.intent.action.USER_PRESENT") || intent.getAction().equals("android.appwidget.action.APPWIDGET_ENABLED") || intent.getAction().equals("android.intent.action.MY_PACKAGE_REPLACED") || intent.getAction().equals("android.appwidget.action.APPWIDGET_UPDATE")) {
getToken();
getUUID();
getGatewayActivationStatus();
getEnvironment();
appWI.handleClickEvent(context, intent, _refresh);
}
};
static PendingIntent buildButtonPendingIntent(Context context, String event) {
if (!event.equals("OPEN_APP")) {
Intent intent = new Intent(context, AppWidgetProvider.class);
intent.setAction(event);
return PendingIntent.getBroadcast(context, 0, intent, 0);
} else {
Intent intent2 = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(context, 0, intent2, 0);
}
}
Finally, I've found solution to this problem.
We can simply find answer here:
https://developer.android.com/training/monitoring-device-state/doze-standby
To solve the above problem, we can use Alarm Manager.
Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window.
So right after the doze mode finishes, or during a maintenance window, it will automatically execute the code, written in alarm manager service.
You can get help here to use Alarm Manager in your widget from this stackoverflow post:
https://stackoverflow.com/a/14319020/3497865
Hi I am making Android application and I want to make a widget for it. The concept of application is that it gets stt(speech-to-text) string from 'Voicemain_Activity' and put string to created field in 'AddActivity'.And in 'AddActivity' there are a button to call 'Voicemain_Activity'. I was trying to make it to start 'Voicemain_Activity'. So I made widget codes like this.
public class MyAppWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
//CharSequence widgetText = context.getString(R.string.appwidget_text);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_app_widget);
// views.setTextViewText(R.id.appwidget_text, widgetText);
Intent intent=new Intent(context, AddActivity.class);
PendingIntent pe=PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.imageButton_voice, pe);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context,appWidgetManager,appWidgetIds);
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
the 'AddActivity' that makes to get 'Voicemain_Activity' looks like this.
#Override
public void onClick(View v) {
int view = v.getId();
if(view == R.id.Bacode){
finish();
}
else if(view == R.id.Voice){
startActivityForResult(new Intent(this, VoiceMain_Activity.class), MY_UI);
}
}
But this code made the widget to just show me the 'Voicemain_Activity' screen and didn't get the string nor put it to 'AddActivity'. How can I make it to work?
https://developer.android.com/guide/topics/appwidgets/index.html#Configuring
I read this and other tutorials to make Widget with user configuration.
I understood that ConfigurationActivity would initialise the widget, but the widget will be updated with "onUpdate" method in provider class.
Then my question is, how do I make the widget keep the initialised data when onUpdate is called?
For example, this is what I have in configurationActivity, that takes String input from user and set it in textView
public void onClick(View v) {
Context context = getApplicationContext();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_haruhi);
//Get String input.
String test = String.valueOf(name.getText());
remoteViews.setTextViewText(R.id.sinceWhen, test);
//But after 30 min it calls default update??
appWidgetManager.updateAppWidget(mAppWidgetId, remoteViews);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
And this is what I have in Widget provider
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int count = appWidgetIds.length;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_haruhi);
long days=getDays(2011,5,15);
//This field needs to be updated periodically
remoteViews.setTextViewText(R.id.daysText, days+context.getString(R.string.days));
// But this field needs to stay the same as initialised configuration
remoteViews.setTextViewText(R.id.daysText, ????);
Intent intent = new Intent(context, HaruhiWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
for (int i = 0; i < count; i++) {
int widgetId = appWidgetIds[i];
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
One field in widget needs to be updated periodically
but the other one needs to show the String as input by user.
but by the time onUpdate is called, this widget gets reset and the initialise value would be lost.
How do I approach this problem? Should I save all initialised data in SharedPreference and load all the data everytime update signal is received?
I have an app widget and the click event can be received in onUpdate() in my provider.
However, when I try to force close the home launcher, the click event is lost.
I even put breakpoints in all onEnabled(), onReceived()...etc: the connection seems to be lost.
As a result, how can I "re-connect" the button event?
WidgetProvider extends AppWidgetProvider:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.d(TAG, "onUpdate()");
Log.d(TAG, "isLoading: " + CONSTANT.isLoading);
// update each of the widgets with the remote adapter from updateService
// Get all ids
ComponentName thisWidget = new ComponentName(context, ScoreWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
// Build the intent to call the service
Intent intent = new Intent(context.getApplicationContext(), UpdateWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
// Update the widgets via the service
context.startService(intent);
// super.onUpdate(context, appWidgetManager, appWidgetIds);
}
UpdateWidgetService extends Service:
#Override
public void onStart(Intent intent, int startId) {
Log.i(TAG, "Called");
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
for (int i = 0; i < appWidgetIds.length; ++i) {
// Here we setup the intent which points to the StackViewService which will
// provide the views for this collection.
Intent remoteViewsIntent = new Intent(this.getApplicationContext(), ScoreWidgetRemoteViewsService.class);
remoteViewsIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
// When intents are compared, the extras are ignored, so we need to embed the extras
// into the data so that the extras will not be ignored.
remoteViewsIntent.setData(Uri.parse(remoteViewsIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews rv = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.widget_layout);
rv.setRemoteAdapter(appWidgetIds[i], R.id.score_list, remoteViewsIntent);
// Set the empty view to be displayed if the collection is empty. It must be a sibling
// view of the collection view.
rv.setEmptyView(R.id.score_list, R.id.empty_view);
// Bind the click intent for the refresh button on the widget
final Intent refreshIntent = new Intent(this.getApplicationContext(), ScoreWidgetProvider.class);
refreshIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
refreshIntent.setAction(ScoreWidgetProvider.REFRESH_ACTION);
final PendingIntent refreshPendingIntent = PendingIntent
.getBroadcast(this.getApplicationContext(), 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.btn_refresh, refreshPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
// stopSelf();
super.onStart(intent, startId);
}
Make sure that you are using the correct context in your onStart function. Check out getApplicationContext in the onStart part of your code, passing in the wrong type of context can cause errors. Here is a link for more information: Context.
I have widget with 2 buttons button with id refresh and second button with id detailsInfo. First button should trigger widget update, second button to show detailed info (downloaded after widget refreshed).
This is weather widget. Refresh should trigger to download full weather data. Basic weather info should be displayed directly on widget, full data on details activity, launched on detailsInfo button click.
This is my code:
public class AppWidget extends AppWidgetProvider
{
public static String ACTION_DETAILS = "m.m.meteowidget.ACTION_DETAILS";
#Override
public void onReceive(Context context, Intent intent)
{
Log.i("onReceive",intent.getAction());
super.onReceive(context, intent);
}
#Override
public void onUpdate(Context ctxt, AppWidgetManager mgr, int[] appWidgetIds)
{
ComponentName me = new ComponentName(ctxt, AppWidget.class);
final RemoteViews updateViews = new RemoteViews(ctxt.getPackageName(), R.layout.widget_layout);
Intent intent = new Intent(ctxt, AppWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pi = PendingIntent.getBroadcast(ctxt, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.refresh, pi);
Intent intent2 = new Intent(ctxt, DetailsActivity.class);
intent2.setAction(ACTION_DETAILS);
PendingIntent di = PendingIntent.getActivity(ctxt, 0, intent2, 0);
updateViews.setOnClickPendingIntent(R.id.detailsInfo, di);
mgr.updateAppWidget(me, updateViews);
for (int i = 0; i < appWidgetIds.length; i++)
new WeatherInfo(updateViews,appWidgetIds[i],mgr).execute();
}
}
WeatherInfo is class that actually performs weather details download (it extends AsyncTask). As you can see, it gets my updateViews as constructor argument and then sets basic weather info displayed on my widget.
However, I have no idea how to display detailed info activity and pass detailed weather info to it. When I try to run my activity as shown above, my widget fails to load ("Problems loading widget"), without any exception that I can debug.
Any ideas what am I doing wrong?
[edit]
This seems to be (almost) ok:
Widget provider:
#Override
public void onReceive(Context context, Intent intent)
{
Log.i("onReceive",intent.getAction());
super.onReceive(context, intent);
}
#Override
public void onUpdate(Context ctxt, AppWidgetManager mgr, int[] appWidgetIds)
{
ComponentName me = new ComponentName(ctxt, AppWidget.class);
final RemoteViews updateViews = new RemoteViews(ctxt.getPackageName(), R.layout.widget_layout);
Intent intent = new Intent(ctxt, AppWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pi = PendingIntent.getBroadcast(ctxt, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.refresh, pi);
mgr.updateAppWidget(me, updateViews);
Intent intent2 = new Intent(ctxt, DetailsActivity.class);
intent2.setAction(ACTION_DETAILS);
PendingIntent di = PendingIntent.getActivity(ctxt, 0, intent2, 0);
updateViews.setOnClickPendingIntent(R.id.detailsInfo, di);
mgr.updateAppWidget(me, updateViews);
for (int i = 0; i < appWidgetIds.length; i++)
new WeatherInfo(updateViews,appWidgetIds[i],mgr).execute();
}
My async task:
public class WeatherInfo extends AsyncTask<String, Void, Map>
{
private RemoteViews views;
private int WidgetID;
private AppWidgetManager WidgetManager;
private DetailsActivity detailsActivity;
public WeatherInfo(RemoteViews views, int appWidgetID, AppWidgetManager appWidgetManager)
{
this.views = views;
this.WidgetID = appWidgetID;
this.WidgetManager = appWidgetManager;
}
#Override
protected Map doInBackground(String... strings)
{
Document doc = null;
try
{
doc = Jsoup.connect("http://meteo.uwb.edu.pl/").get();
}
catch (IOException e)
{
Log.e("","Connection failed: " + e.getMessage());
return null;
}
Elements tables = doc.select("td");
Elements headers = tables.get(2).select("b");
Elements vals = tables.get(3).select("b");
Map all = new LinkedHashMap();
for (int i=0;i<headers.size() ; i++)
all.put(headers.get(i).text(),vals.get(i).text());
Global.weatherInfo = all;
return all;
}
#Override
protected void onPostExecute(Map map)
{
if(map==null) return;
String txt = "";
String temp = (String) map.values().toArray()[0];
String hum = (String) map.values().toArray()[1];
String pressure = (String) map.values().toArray()[2];
String temp2 = "Odczuwalna: " + map.values().toArray()[3];
views.setTextViewText(R.id.info_temp, temp);
views.setTextViewText(R.id.info_temp2, temp2);
views.setTextViewText(R.id.info_hum, hum);
views.setTextViewText(R.id.info_pressure, pressure);
WidgetManager.updateAppWidget(WidgetID, views);
}
}
So I there is Global class with weatherInfo static field to share value between my thread and details activity.
However, there are 2 things that I have no idea how to fix:
- if activity is destroyed (removed from last app list in Android), after I press details button on my widget, activity is empty (bacause Global.weather info is null). I need to trigger widget refresh again and then lanunch my activity
- if I try to set Global.weatherInfo inside PostExecute method my widgets fails to show, without any exception thrown - why?
- I also tried to trigger my async task on create my activity. So i created second WeatherInfo constructor and passed DetailSActivity object into this, to be able to refresh my activity. Even if I don't use that second constructor, my widgets again fails to load without any exception.
I'm confused, can anybody tell me what's going on here? And how to solve my problem?
Create AsyncTask separately. Return the values from postexecute() method. Handler will give you better solution to handle response of asynktask.
Call this asynctask before populating the values in UI components. Handle error case separately either by dialogue box whatever you wish.
follow the link for clearance in handler
I made it working by storing data in sqlite database. So, after widget refresh, all data are saved to database. Database is also for data cache, so if there is no internet connection, widget disaplays cached data. The same cached data will be loaded to be displayed on my activity.