简体   繁体   English

Android:单击窗口小部件时活动未启动

[英]Android: Activity not launching when clicking widget

I have a widget whose layout has two buttons. 我有一个小部件,其布局有两个按钮。 My code follows, 我的代码如下

public void onReceive(Context context, Intent i) {

    AppWidgetManager mgr = AppWidgetManager.getInstance(context);

    Intent intent = new Intent(context, Activity1.class);
    PendingIntent pendingLayout = PendingIntent.getActivity(context, 0, intent, 0);


    Intent searchIntent = new Intent(context, Activity2.class);
    PendingIntent searchPendingLayout = PendingIntent.getActivity(context, 0, searchIntent, 0);

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

    views.setOnClickPendingIntent(R.id.widgetbutton, pendingLayout);
    views.setOnClickPendingIntent(R.id.widgetsearch, searchPendingLayout);

    ComponentName comp = new ComponentName(context,
            RecentTaskWidget.class.getName());

    mgr.updateAppWidget(comp, views);
}

The widgetbutton and the widgetsearch are the two views in the layout. widgetbutton和widgetsearch是布局中的两个视图。 I am getting the corresponding views from the remoteviews object and adding the pending layout to each of them. 我从remoteviews对象获取相应的视图,并将待处理的布局添加到每个视图。 However, the activities are not starting. 但是,活动尚未开始。 Is there anything wrong with the code? 代码有什么问题吗?

Thx! 谢谢!

Override onUpdate() method of your AppWidgetProvider and add this code to it's body: 重写AppWidgetProvider onUpdate()方法,并将以下代码添加到其主体中:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    AppWidgetManager mgr = AppWidgetManager.getInstance(context);
    Intent intent = new Intent(context, Activity1.class);
    PendingIntent pendingLayout = PendingIntent.getActivity(context, 0, intent, 0);
    Intent searchIntent = new Intent(context, Activity2.class);
    PendingIntent searchPendingLayout = PendingIntent.getActivity(context, 0, searchIntent, 0);
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.searchwidget);
    views.setOnClickPendingIntent(R.id.widgetbutton, pendingLayout);
    views.setOnClickPendingIntent(R.id.widgetsearch, searchPendingLayout);
    ...
    appWidgetManager.updateAppWidget(appWidgetIds, views);
}       

You can see this page for more details. 您可以查看此页面以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM