可能重复:
How to launch activity from android home screen widget
从应用程序主屏幕小部件启动活动的最简单代码是什么?
到目前为止我的代码没有工作,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>
答案 0 :(得分:4)
这终于奏效了:
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);
}
}