How to connect an android widget to my android app

2019-06-06 14:00发布

问题:

I want to combine my widget and one of my android application..

Is it possible to do that?

My plan is, once user open up my android widget, the widget will directly open up my android application?

Is there any way how?

I made some method here from my widget class:

public class ExampleAppWidgetProvider extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int i = 0; i < appWidgetIds.length; i++) {
int appWidgetId = appWidgetIds[i];

Intent intent = startActivity(new Intent("com.xxx.yyy.widget.FlamingoActivity"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);

RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget1);

views.setOnClickPendingIntent(R.id.Image, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}

I tried to call the second app, FlamingoActivity, but its failing.. :(

NOT THE FULL SOLUTION:

I should change this line

Intent intent = startActivity(new Intent("com.xxx.yyy.widget.FlamingoActivity"));

to this:

Intent intent = new Intent(context, FlamingoActivity.class);

回答1:

You need to set an onClickpendingIntent on your widget

   Intent intent = new Intent(context, ExampleActivity.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
     RemoteViews views = new 
                 RemoteViews(context.getPackageName(),R.layout.appwidget_provider_layout);
      views.setOnClickPendingIntent(R.id.button, pendingIntent);

And also See this question Launching activity from widget



回答2:

The activity that you are trying to call needs to be public (exported) in the manifest of its app. There is nothing special about starting activities from a widget, other than the fact that you use a PendingIntent to allow the widget to work as a part of your app (it runs inside the launcher app).