如何将一个字符串从小部件发送到活动?

huangapple 未分类评论47阅读模式
英文:

How to send a string from widget to Activity?

问题

以下是翻译好的内容:

我在我的小部件中有一些按钮,我想发送一个意图额外的字符串并打开我的主活动。当涉及从活动到活动的情况时,这个过程似乎足够简单,但是我无法使其从小部件到活动起作用。我在这里看到了一些其他的答案,但我肯定是漏掉了什么,因为我的日志没有显示出来。

这是我的updateAppWidget方法:

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {

    // 构造RemoteViews对象
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.budget_keeper_widget);

    Intent intent = new Intent(context, MainActivity.class);
    intent.putExtra("widget_one", "widget_one");
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.button_1_widget, pendingIntent);

    // 通知小部件管理器更新小部件
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

这是我的MainActivity:

@Override
protected void onNewIntent(Intent intent) {

    super.onNewIntent(intent);
    String intentFromWidget = intent.getStringExtra("widget_one");
    Log.e("WIDGET MAIN INTENT", intentFromWidget);

}

这样可以打开我的活动,但是我的日志中没有额外的意图。有什么诀窍可以让这个工作起来呢?

谢谢!

英文:

I have some buttons in my widget that I want to send a intent extra string and also open my Main Activity. This process seems easy enough when it comes from Activity to Activity but I can't make it work from Widget to Activity. I saw some other answers here but I must be missing something because my Logs are not going off.

Here is my updateAppWidget method:

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {

    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.budget_keeper_widget);

    Intent intent = new Intent(context, MainActivity.class);
    intent.putExtra("widget_one", "widget_one");
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.button_1_widget, pendingIntent);


    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

Here's my MainActivity

@Override
protected void onNewIntent(Intent intent) {

    super.onNewIntent(intent);
    String intentFromWidget = intent.getStringExtra("widget_one");
    Log.e("WIDGET MAIN INTENT", intentFromWidget);

}

This opens my Activity fine but I get no intent extra in my Logs. What's the trick to making this work?

Thank you!

huangapple
  • 本文由 发表于 2020年7月26日 04:10:55
  • 转载请务必保留本文链接:https://java.coder-hub.com/63093107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定