0

I want to load the image from url, as well as the text show in below the image. Like this,

Widget Example

  1. Alignment on ImageView & TextView, here is my code but doesn't shows the desired layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00FFFF"
        android:padding="0.1dp">
    
    <TextView android:text="@string/widgetUrl"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.8"
    android:layout_gravity="center_vertical"
    android:textColor="#000000">
    </TextView>
    <TextView android:text="@string/widgetTitle"
    android:id="@+id/widgetTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.8"
    android:layout_gravity="center_vertical"
            android:layout_alignParentBottom="true"  
            android:layout_centerHorizontal="true"
    android:textColor="#ffffff">
    </TextView>
    <ImageView android:id="@+id/widgetBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.5"
    android:src="@drawable/ic_launcher"
    android:layout_gravity="center_vertical">
    </ImageView>
    
    </LinearLayout>
    
  2. How to load the image from web and display on the layout in java code? Below is my widget provider code:

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    
    Log.i(WIDGETTAG, "onUpdate");
    
    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];
    
        Log.i(WIDGETTAG, "updating widget[id] " + appWidgetId);
    
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    
        /* View setup */
        views.setInt(R.id.widgetTitle, "setBackgroundColor", Color.argb(150, 0, 0, 0));
    
        Intent intent = new Intent(context, ChopInkService.class);
        intent.setAction(ChopInkService.UPDATE_IMAGE);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    
        views.setOnClickPendingIntent(R.id.widgetBackground, pendingIntent);
        Log.i(WIDGETTAG, "pending intent set");
    
        // Tell the AppWidgetManager to perform an update on the current App Widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
    
  3. What is the job for Service and AppWidgetProvider?

    • Load image from url is the job of service or AppWidgetProvider?
    • View setup should put in service or AppWidgetProvider?
  4. How can I redirect user to play store when user tapped on the widget?

Thanks in advanced. I'm a newbie, apologize that if I asked a stupid question.

Js Lim
  • 3,329
  • 5
  • 32
  • 65

3 Answers3

4

Available Widget views & Layout

A widget is restricted in the View classes it can use. As layouts you can use the FrameLayout, LinearLayout and RelativeLayout classes. As views you can use AnalogClock, Button, Chromometer, ImageButton, ImageView, ProgressBar and TextView.

As of Android 3.0 more views are available: GridView, ListView, StackView, ViewFlipper and AdapterViewFlipper. This adapter Views require that you define a collection view widget which is described later in this tutorial.

The only interaction that is possible on the Views of a Widget is via on OnClickListener. This OnClickListener can be registered on a widget and is triggered by the user.

AppWidgetProvider

Your BroadcastReceiver typically extends the AppWidgetProvider class.

The AppWidgetProvider class implements the onReceive() method, extracts the required information and calls the following widget lifecycle methods.

As you can add several instances of a widget to the homescreen you have lifecycle methods which are called only for the first instance added / removed to the homescreen and others which are called for every instance of your widget.

Lifecycle of Widget

onEnabled() -Called the first time an instance of your widget is added to the homescreen

onDisabled() -Called once the last instance of your widget is removed from the homescreen.

onUpdate() -Called for every update of the widget. Contains the ids of appWidgetIds for which an update is needed. Note that this may be all of the AppWidget instances for this provider, or just a subset of them, as stated in the methods JavaDoc. For example if more than one widget is added to the homescreen, only the last one changes (until reinstall).

onDeleted() -Widget instance is removed from the homescreen

All long running operations in these methods should be performed in a service, as the execution time for a broadcast receiver is limited. Using asynchronous processing in the onReceive() method does not help as the system can kill the broadcast process after his onReceive() method.

For more details about widget check How to create widget in Android?

Tutorial1
Tutorial2

GrIsHu
  • 28,433
  • 10
  • 61
  • 99
0

Hi you can check this tutorial for Loading Image from URL (Http) .

Try the following code :

URL Image widget provider class

public class URLImageAppWidgetProvider extends AppWidgetProvider {
    public static String TAG = "URLImageWidget";

    public static class Size_1_1 extends URLImageAppWidgetProvider {}
    public static class Size_1_2 extends URLImageAppWidgetProvider {}
    public static class Size_1_4 extends URLImageAppWidgetProvider {}
    public static class Size_2_2 extends URLImageAppWidgetProvider {}

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                    int[] appWidgetIds) {
            super.onUpdate(context, appWidgetManager, appWidgetIds);

            SharedPreferences urls = context.getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
            for (int id : appWidgetIds) {
                    String url = urls.getString("url_" + id, "");
                    update(context, appWidgetManager, id, url);
            }       

    }

@Override
public void onDeleted(Context context, int[] appWidgetIds) {
    super.onDeleted(context, appWidgetIds);

    SharedPreferences urls = context.getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
    SharedPreferences.Editor urls_editor = urls.edit();
            for (int id : appWidgetIds) {
                    urls_editor.remove("url_" + id);
            }

            urls_editor.commit();

}

    public static void update(final Context context, final AppWidgetManager appWidgetManager, final int id, final String url) {
            new Thread() {
                    public void run() {
                            Bitmap img = getBitmapFromUrl(url);
                            if (img != null) {
                                    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
                                    views.setImageViewBitmap(R.id.img, img);
                                    appWidgetManager.updateAppWidget(id, views);    
                            }
                    }
            }.start();
    }

private static Bitmap getBitmapFromUrl(final String url) {
    try {
            return BitmapFactory.decodeStream(((java.io.InputStream)new java.net.URL(url).getContent()));
    } catch (Exception e) {
            return null;
    }

   }
 }

Here is URL Image widget Configuration class

    public class URLImageAppWidgetConfiguration extends Activity {
    private int id;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.configuration);
        setResult(RESULT_CANCELED);

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            id = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, 
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        if (id == AppWidgetManager.INVALID_APPWIDGET_ID) {
        finish();
    }

    }

    public void addWidget(View v) {
            SharedPreferences urls = getSharedPreferences("urls.conf", Context.MODE_PRIVATE);
            SharedPreferences.Editor urls_editor = urls.edit();

            String url = ((TextView) findViewById(R.id.url)).getText().toString();
            if (!url.startsWith("http://")) url = "http://" + url;
            urls_editor.putString("url_" + id, url);
            urls_editor.commit();

            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
            URLImageAppWidgetProvider.update(this, appWidgetManager, id, url);

    setResult(RESULT_OK, 
                      new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
    );
    finish();
    }
   }
androidgeek
  • 3,299
  • 1
  • 13
  • 27
  • oh, I'm sorry. Now the problem is I can't load the image from url and display to ImageView. `remoteViews.setImageViewBitmap(R.id.widget_background, getBitmapFromUrl("https://www.getchopink.com/assets/default/images/for-your-business-6.png"));` which is the method that you provided to me – Js Lim Mar 05 '13 at 07:06
  • You can use this method to get the image from URL `private static Bitmap getBitmapFromUrl(final String url) { try { return BitmapFactory.decodeStream(((java.io.InputStream)new java.net.URL(url).getContent())); } catch (Exception e) { return null; }` – androidgeek Mar 05 '13 at 07:10
  • ya, I'm calling this method, but it return null. `e.getMessage()` also `null` – Js Lim Mar 05 '13 at 07:18
0

see this.

How to create android app with app widget in single application

This is helpful for you if you find out any problem then let me know.

Community
  • 1
  • 1
Harshid
  • 5,438
  • 4
  • 33
  • 49