我一直在尝试设置主屏幕小部件上的按钮以重新打开ConfigActivity。但是我无法做到。
我已经尝试了一下stackoverflow,android dev指南以及其他非官方教程,并且一直在尝试所有建议的方式,但到目前为止还没有运气。
这是AppWidgetProvider()
中的onUpdate()RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent intent = new Intent(context, ConfigActivity.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_refresh, pendingIntent);
我尝试过额外,数据,标志,没有运气。
ConfigActivity只是将小部件放在主屏幕上时首次启动的Activity。 R.layout.widget是小部件的布局 R.id.widget_refresh是按钮ID
我还有什么需要做的吗?我缺少什么?
我的ConfigActivity.java
public class ConfigActivity extends Activity implements android.view.View.OnClickListener {
private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configactivity);
Intent intent = new Intent();
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(Activity.RESULT_CANCELED, intent);
assignAppWidgetId();
findViewById(R.id.widgetactivity_button).setOnClickListener(this);
}
/**
* Widget configuration activity,always receives appwidget Id appWidget Id =
* unique id that identifies your widget analogy : same as setting view id
* via @+id/viewname on layout but appwidget id is assigned by the system
* itself
*/
private void assignAppWidgetId() {
Bundle extras = getIntent().getExtras();
if (extras != null)
appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
public void onClick(View v) {
if (v.getId() == R.id.widgetactivity_button)
startWidget();
}
/**
* This method right now displays the widget and starts a Service to fetch
* remote data from Server
*/
private void startWidget() {
// this intent is essential to show the widget
// if this intent is not included,you can't show
// widget on homescreen
Intent intent = new Intent();
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(Activity.RESULT_OK, intent);
// start your service
// to fetch data from web
Intent serviceIntent = new Intent(this, RemoteFetchService.class);
serviceIntent
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startService(serviceIntent);
// finish this activity
this.finish();
}
}
编辑:我已经解决了问题,将意图放在onReceive()而不是onUpdate()上,我可以让小部件再次接收正常的点击。