Do not create widget - android

Hello this is simple question
i create widget and test this is my simple code :
#Override
public void onReceive(Context context, Intent intent) {
ComponentName thisAppWidget = new ComponentName(context, MyWidget.class);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
Log.d(" widget ids : " + Arrays.toString(ids) );
setResultCode(0);
}
But i have got red square on home screen .. ?
My widget provider configuration :
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="80dp"
android:minHeight="80dp"
android:previewImage="#drawable/example_appwidget_preview"
android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen|keyguard"
>
</appwidget-provider>

But i have got red square on home screen .. ?
This could be the preview image you have set in widget provider xml.
When the widget is added in home screen, the onUpdate() method will be called, where you can set the remote layout for the widget like this.
public class CustomAppWidgetProvider extends AppWidgetProvider{
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
}
You can also set a pending intent to an activity/service to be invoked when the whole widget or an child item in the widget is clicked
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
remoteViews.setOnClickPendingIntent(R.id.imageView1,pendingIntent);
So, here in the widget layout there is a textview , and when the user click on the textview the MainActivity will be launched.

You have to set an layout file to your appwidget-provider:
android:initialLayout="#layout/widget_view"
In this layout file you have to put Buttons, Images, TextViews etc. whatever you need.

Related

Widget refresh from inside application

Good Day! I want to add text from inside application to widget, i have a main activity and it has list view and lots of text contents and it has a button to add the text to widget via shared preference, it's works fine when i close the widget and recreate it only, otherwise it's not automatically refresh.if anyone know; how to solve this please help me. here i attached the widget code below.
public class WidgetMaster extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
Intent intentHome = new Intent(context, MainActivity.class);
PendingIntent pendingIntentHome = PendingIntent.getActivity(context, 0, intentHome, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_master);
views.setOnClickPendingIntent(R.id.wid_home, pendingIntentHome);
final SharedPreferences sharedPreferencestoWi = context.getSharedPreferences(String.valueOf(R.string.addTextToWidgetPref), MODE_PRIVATE);
String forWidget = sharedPreferencestoWi.getString("textToWidget", "");
String dum = "add from reading";
if(forWidget.equals("")){
views.setTextViewText(R.id.dum_appwidget_text, dum);
appWidgetManager.updateAppWidget(appWidgetId, views);
} else {
views.setTextViewText(R.id.appwidget_text, forWidget);
views.setViewVisibility(R.id.appwidget_text, 0);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
#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);
}
}
#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
}
}
How do you update the widget from mainActivity?
In the widget configuration file you can specify a fixed update interval. The smallest update interval is 1800000 milliseconds (30 minutes).
But its better to update widget programmatically, to do this You should send a broadCast to update widget and use a
method like alarmManager or Handler for a repeating task for example you can use the following broadCast to update widget form mainActivity:
Intent intent = new Intent(this, WidgetMaster.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
int[] ids = AppWidgetManager.getInstance(getApplication())
.getAppWidgetIds(new ComponentName(getApplication(),WidgetMaster.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
sendBroadcast(intent);

Widget custom icon Android

I would like to make a custom image for a widget, i tried
views.setImageViewResource(R.id.red_button, R.drawable.button_default);
and
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.button_default);
views.setImageViewBitmap(R.id.red_button, icon);
but it says problem loading widget all the time, no matter what I try, am I missing something? can someone point me to the right documantion/what to do?
Edit:
full xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_green_dark"
android:orientation="vertical"
android:padding="#dimen/widget_margin">
<ImageButton
android:id="#+id/red_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Button"
app:srcCompat="#drawable/button_default" />
</LinearLayout>
code:
public class NewAppWidget 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.new_app_widget);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.red_button, pi);
views.setTextViewText(R.id.red_button, widgetText);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.button_default);
views.setImageViewBitmap(R.id.red_button, icon);
//views.setImageViewResource(R.id.red_button, R.drawable.button_default);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#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);
}
}
#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
}
}
Thanks!
The error message ("problem loading widget") is not caused by any problems with displaying the drawable, it is showing because of this line in your code:
views.setTextViewText(R.id.red_button, widgetText);
You can only use setTextViewText(int, CharSequence) with resource ids for Views extending from TextView (according to the docs, it's equivalent to TextView.setText(CharSequence) ).
The resource id R.id.red_button belongs to an ImageButton which extends from ImageView not from TextView, that's why you get the error message.
So if you want to show some text you need to add a Textview to your app widget's layout.

Updating text in a widget on an event

I created a class that downloads some text from the internet and I want to take that text and update a TextView in my widget. I know that the event (OnDownloadCompleteListener) is getting triggered because I'm Logging it but I can't figure out how to update the TextView from within that event. I know it's a newbie mistake, just not sure what I'm missing.
public class Widget extends AppWidgetProvider{
InternetText internettext; //Handles downloading the text from the internet
RemoteViews views;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.tvWidgetVerse, pendingIntent);
internettext = new InternetText(context);
internettext.setOnDownloadCompleteListener(new OnDownloadCompleteListener() {
#Override
public void onEvent() {
TheText thetext = internettext.downloadedText(); //The text object
Log.i("", "Widget Text Downloaded " + thetext.getText()); //This fires so I know we've downloaded the text
TextStyling textStyle = new TextStyling();
//*****THIS IS WHERE I'M HAVING THE PROBLEM********
views.setTextViewText(R.id.tvWidgetText, Html.fromHtml(textStyle.boldWords(thetext.getText()))); //this never updates
}
});
internettext.getText();
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
Ok, I figured it out. I have to call appWidgetManager.updateAppWidget() from within the event. I knew it was a no-brainer...
appWidgetManager.updateAppWidget(appWidgetId, views);
which also means I have to make appWidgetManager and appWidgetId final
public void onUpdate(Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
...
}

Changing from initial layout to main layout for widget

I've created a widget for my application, but I require a initial loading layout before I show my main widget layout. I have made a load up layout as a initial and my main layout. I tried to use RemoteViews to show up my main widget layout after my stuff has finished loading at onUpdate method but it does not show up.
Is there any way to switch from the initial layout to the main layout?
Edit
Sorry for the late reply, hope I am showing the right blocks. What I did was to set the initial layout at the app widget properties and change to the actual layout that i am showing at the onUpdate method via a service in another class file.
Here are my codes:
The Widget info
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="#layout/initial_layout"
android:minHeight="146dp"
android:minWidth="294dp"
android:updatePeriodMillis="1800" >
</appwidget-provider>
This is what i typed for my onUpdate method:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
//start service
Intent myIntent = new Intent(context, WeatherNotificationService.class);
context.startService((myIntent));
}
Here is the code i typed within the service method.
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(WeatherNotificationService.this.getApplicationContext());
ComponentName thisWidget = new ComponentName(getApplicationContext(),SafetyWidget.class);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
new CommonOpearation().showToast(getApplicationContext(), appWidgetIds.length+"");
for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetID = appWidgetIds[i];
DateFormat formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
formatter.setLenient(false);
Date a= new Date();
RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(),R.layout.widget_layout);
remoteViews.setTextViewText(R.id.todayDate,formatter.format(a));
remoteViews.setTextViewText(R.id.psiTime,currentNowCast.getCurrentPsiObj().getDatenTime());
remoteViews.setTextViewText(R.id.psiTV,currentNowCast.getCurrentPsiObj().getPsi());
remoteViews.setTextViewText(R.id.textViewTodayTemp,currentNowCast.getCurrentTemp().getTemp());
remoteViews.setTextViewText(R.id.textViewNearestRegion, nowCastWeather.getNwo().getRegion());
remoteViews.setTextViewText(R.id.hospTV, contact.getName());
appWidgetManager.updateAppWidget(appWidgetID, remoteViews);
RemoteViews function is to show up the appropriate layout when it is called at onUpdate? This is puzzling...

Widget ImageButton listener not allways called

I have a simple Widget (Android 2.1) containing just a LinearLayout, itself containing an ImageButton.
The ImageButton has a on-click listener.
The problem is: If I put several of this same widget on my home screen, some are working (listener called when button pressed), and some are not! I cannot see any pattern in which are working and which are not.
Here is the widget layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ImageButton01"
android:src="#drawable/widget_running"
android:background="#null">
</ImageButton>
And here is the widget provider code:
public class GPAppWidgetProvider extends AppWidgetProvider {
private String mTag = getClass().getSimpleName();
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
Log.e(mTag, "onUpdate ");
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
Log.e(mTag, "widget onUpdate one loop");
int appWidgetId = appWidgetIds[i];
// Create an Intent
Intent intent = new Intent(context, GPService.class).setAction(ACTION_WIDGET_TOGGLE_PAUSE);
intent.putExtra("widgetId", appWidgetId);
PendingIntent pauseIntent = PendingIntent.getService(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.gp_appwidget);
views.setOnClickPendingIntent(R.id.ImageButton01, pauseIntent);
// widget update
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
I had the same problem.
Don't forget to set a different "requestCode" when you call "getService" :
public static PendingIntent getService (Context context, int requestCode, Intent intent, int flags)
And make sure your "appWidgetId" is different for each widget.

Categories

Resources