我如何启动一个活动与家庭的Widget [复制](How Do I Launch an Activi

2019-10-16 13:44发布

可能重复:
如何从Android主屏幕小部件发起活动

请告诉我最简单的代码来启动从应用的主屏幕小部件的活动?

我至今不工作,没有什么的代码显示在logcat的..?

窗口小部件在其内具有图像和当图像被窃听,应该启动该应用程序。 寻找一个片段。

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);
    }
}

窗口小部件布局:

<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>

Answer 1:

这最后的工作:

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);
    }
}


文章来源: How Do I Launch an Activity with Home Widget [duplicate]