How Do I Launch an Activity with Home Widget [duplicate]

醉酒当歌 提交于 2019-12-24 17:16:35

问题


Possible Duplicate:
How to launch activity from android home screen widget

Whats the simplest code to launch an activity from the applications home-screen widget?

The code I have so far doesnt work and nothing shows in LogCat..??

The widget has an image within it and when the image is tapped, should launch the application. Looking for a snippet.

public class MyWidget extends AppWidgetProvider
{
    // Create an Intent to launch activity from ImageView
    @Override
    public void onEnabled(Context context)
    {
    Intent intent = new Intent(Intent.ACTION_MAIN, null);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    ComponentName comp = new ComponentName(context.getPackageName(),MyWidget.class.getName());
    intent.setComponent(cn);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent myPI = PendingIntent.getActivity(context, 0, intent, 0);

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.content);//<-THE LAYOUT W/I THE MainActivity CLASS??

    views.setOnClickPendingIntent(R.id.widgetLauncher, myPI);//<-THE IMAGEVIEW ID??

    AppWidgetManager mgr = AppWidgetManager.getInstance(context);
    mgr.updateAppWidget(comp, views);
    }
}

Widget Layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/widgetLauncher"
        android:layout_width="258dp"
        android:layout_height="54dp"
        android:layout_centerInParent="true"
        android:src="@drawable/wgt_logo" >
    </ImageView>

</RelativeLayout>

回答1:


This finally worked:

public class MyWidget extends AppWidgetProvider
{
    // Create an Intent to launch activity
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds)
    {
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.home_widget);
    // When we click the widget, we want to open our main activity.
    Intent launchActivity = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchActivity, 0);
    remoteViews.setOnClickPendingIntent(R.id.widget, pendingIntent);;

    ComponentName thisWidget = new ComponentName(context, MyWidget.class);
    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    manager.updateAppWidget(thisWidget, remoteViews);
    }
}


来源:https://stackoverflow.com/questions/10032778/how-do-i-launch-an-activity-with-home-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!