单击小部件后如何启动活动?

时间:2015-07-25 18:29:45

标签: android view widget android-widget android-appwidget

我想创建一个带图标的简单小部件来启动我的应用。

我有小部件及其布局正常工作,但我找不到点击它时启动应用程序的方法。

这是小部件类:

public class LauncherWidget extends AppWidgetProvider {

    private static final String ACTION_CLICK = "ACTION_CLICK";

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager) {

        Intent intent = new Intent(context, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Attach the intent to the widget's button.
        final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        remoteViews.setOnClickPendingIntent(R.id.widget, pendingIntent);

    }

}

我从未创建过小部件,因此我不知道该怎么做。 我已经在这里查看了更多信息,但是我能找到的是在点击时更新其内容的小部件,但我尝试使用他们的代码但是它无效。

提前致谢。

2 个答案:

答案 0 :(得分:4)

这对我有用......

onUpdate方法代码应为:

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

            try {
                Intent intent = new Intent("android.intent.action.MAIN");
                intent.addCategory("android.intent.category.LAUNCHER");

                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.setComponent(new ComponentName(context.getPackageName(),
                        "Activity.class"));
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        context, 0, intent, 0);
                RemoteViews views = new RemoteViews(context.getPackageName(),
                        R.layout.widget_layout);
                views.setOnClickPendingIntent(R.id.widget, pendingIntent);
                appWidgetManager.updateAppWidget(appWidgetId, views);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(context.getApplicationContext(),
                        "There was a problem loading the application: ",
                        Toast.LENGTH_SHORT).show();
            }

        }
    }

答案 1 :(得分:0)

在小部件AppWidgetProvider类的onUpdate()方法中使用此代码段:

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

    PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);

    remoteViews.setOnClickPendingIntent(R.id.widget, configPendingIntent);
    appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}