将数据从小部件发送到活动

psv*_*psv 4 android android-widget

我正在尝试将数据从我的小部件发送到我的活动。我已经看到了几个关于小部件方面的主题,但我没有成功地在我的活动中获取数据。

请参阅将数据从小部件传递到应用程序

在我的 Activity 中,我尝试在 onStart() 方法中执行以下操作:

Intent intent = getIntent();
if(intent.getStringExtra("he")!=null)
  LogWrapper.debug(MainActivity.class, "DATA "+intent.getStringExtra("he"));
else
  LogWrapper.debug(MainActivity.class, "DATA null"); 
Run Code Online (Sandbox Code Playgroud)

但意图始终为空。

小部件提供商方:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
LogWrapper.info(DefibWidgetProvider.class,"in onUpdate!");
final int N = appWidgetIds.length;

// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
  int appWidgetId = appWidgetIds[i];

  // Create an Intent to launch MainActivity
  Intent intent = new Intent(context, MainActivity_.class);
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
  intent.putExtra("he","Hello !");
  PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

  // Get the layout for the App Widget and attach an on-click listener
  // to the button
  RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_defib);
  views.setOnClickPendingIntent(R.id.refreshButton, pendingIntent);

  // Tell the AppWidgetManager to perform an update on the current app widget
  appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
Run Code Online (Sandbox Code Playgroud)

上下文:我的应用程序包含 Google 地图。我的小部件中有 2 个按钮,当用户单击这些按钮之一时,我想打开主要活动并将地图集中在特殊的经/纬度上。

你能帮我让它工作吗?谢谢

Chi*_*ang 5

根据您建议的链接,您将在 onNewIntent 方法中获取意图的数据,

@Override
protected void onNewIntent(Intent intent) {
    // TODO Auto-generated method stub
    super.onNewIntent(intent);
}
Run Code Online (Sandbox Code Playgroud)

从该方法内部获取您的意图数据。