gpt4 book ai didi

Android 小部件 onUpdate()

转载 作者:行者123 更新时间:2023-11-29 14:01:29 25 4
gpt4 key购买 nike

所以,我开发了一个 android 小部件,它应该用作按钮。我使用了这里给出的基本代码:http://developer.android.com/guide/topics/appwidgets/index.html单击该按钮时,将启动一个 Activity 。这每次都很好用!但是,当我记录单击按钮的时间时,我只得到了第一次。为什么会这样?

这是我被要求的代码:

public class ExampleAppWidgetProvider extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
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];
Log.d("myButton","This is only called once.Why????????")
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, ExampleActivity.class);
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.appwidget_provider_layout);
views.setOnClickPendingIntent(R.id.button, pendingIntent);

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

最佳答案

该日志语句位于小部件的 onUpdate 方法中,并且仅在创建小部件时以及在小部件的更新周期内被调用。要让它在点击时登录,您可以执行以下两项操作之一。

一个。将log语句放在ExampleActivity的onCreate方法中

B.更改挂起的 Intent 以使用标志更新 AppWidgetProvider,然后覆盖 onReceive 方法以执行日志声明,然后启动 ExampleActivity(如果存在标志)。例如:

Intent intent = new Intent(context, ExampleAppWidgetProvider.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(SOME_FINAL_STRING, true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

然后在onReceive方法中:

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle extras = intent.getExtras();

if(AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) && extras != null && extras.getBoolean(SOME_FINAL_STRING) == true){
Log.d("myButton","Should no longer be called once!");
Intent newIntent = new Intent(context, ExampleActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
} else {
super.onReceive(context, intent);
}
}

关于Android 小部件 onUpdate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9311615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com