代码之家  ›  专栏  ›  技术社区  ›  Bryan W

将Android意向操作从打开URI更改为显示Toast?

  •  1
  • Bryan W  · 技术社区  · 7 年前

    我正在尝试让我的小部件使用onclick操作来提示刷新。我找到了一些可用的演示代码,但它在浏览器中打开了一个URI。我很难用更简单的东西替换uri操作,比如显示一个toast。我已经标记了我试图改变的行,但我不知道如何让Android设置不同于action.view的操作。

    public class NewAppWidget extends AppWidgetProvider {
    
    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
    
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
    
        //I AM TRYING TO CHANGE THIS INTENT
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    
        views.setOnClickPendingIntent(R.id.refresh, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
    
    @Override //Nothing changed here
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
            }
        }
    }
    

    具体的行是

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com/"));
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Bryan W    7 年前

    我完全出乎意料地做到了这一点。我跟踪了这篇文章,但把我的意图声明留在了原处。结果是:

    Intent intent = new Intent(context, NewAppWidget.class);
            intent.setAction(refresh);
            intent.putExtra("appWidgetId", appWidgetId);
    
            views.setOnClickPendingIntent(R.id.refresh, PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_UPDATE_CURRENT));
            appWidgetManager.updateAppWidget(appWidgetId, views);
    

    然后是OnReceive:

    @Override
        public void onReceive(Context context, Intent intent) {
            if(refresh.equals(intent.getAction())) {
                Toast.makeText(context, "Clicked", Toast.LENGTH_LONG).show();
            }
        }
    

    为了清晰起见,编辑:intent.getaction()需要是接收器的intent筛选器中注册的操作。

    推荐文章