0

I'm trying to make a widget with two buttons that open different applications. Can't understand why the buttons don't work. Can anybody help? The mainactivity java class is shown below.

I have been a little confused about adding buttons to a widget but thought I had completed everything correctly.

package com.example.widget;

import com.example.carwidget.R;

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.widget.RemoteViews;

public class MainActivity extends AppWidgetProvider {


@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main_activity);

    Intent active = new Intent();
    active.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    active.addCategory(Intent.CATEGORY_LAUNCHER); 
    active.setAction(Intent.ACTION_MAIN);
    active.setComponent(new ComponentName("com.spotify.mobile.android.ui", null)); 
    PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
    remoteViews.setOnClickPendingIntent(R.id.button1, actionPendingIntent);

    active = new Intent();
    active.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    active.addCategory(Intent.CATEGORY_LAUNCHER); 
    active.setAction(Intent.ACTION_MAIN);
    active.setComponent(new ComponentName("com.google.android.apps.maps", null)); 
    actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
    remoteViews.setOnClickPendingIntent(R.id.button2, actionPendingIntent);

    appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getComponent().equals("com.spotify.mobile.android.ui")) {
        context.startActivity(intent);
    } else if (intent.getComponent().equals("com.google.android.apps.maps")) {
        context.startActivity(intent);;
    } else {
        super.onReceive(context, intent);
    }
}
}

1 Answers1

0

See the constructor for ComponentName here. The name of the class can not be null.

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

    // ......

    active.setComponent(new ComponentName("com.spotify.mobile.android.ui", null));
    // ......
    active.setComponent(new ComponentName("com.google.android.apps.maps", null));

    // ......

}
janzoner
  • 1,380
  • 1
  • 10
  • 19