我想为一个应用程序创建一个小部件,并已经编写了widget provider
和configuration
类。小部件布局中只有一张图片,当我点击它时,希望能够打开MyActivity
活动类。在配置布局中有一张红色图片,当我点击该图片时,小部件的图片会改变。问题是当我点击小部件时,它并没有打开MyActivity
。
在哪里应该放置views.setOnClickPendingIntent
?放到appWidgetProvider
里吗?还是放到appWidgetConfiguration
里?还是两者都要放?
问题2是:我是否需要将此代码放入MyActivity
才能通过小部件点击打开它?:sendBroadcast(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME));
以下是我的代码:
appwidget.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
android:id="@+id/imageWidget" />
</LinearLayout>
appWidgetProvider.java
public class OffAppWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget);
views.setOnClickPendingIntent(R.id.imageWidget, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
appWidgetConfiguration.java
public class AppWidgetConfiguration extends Activity{
private int mAppWidgetId;
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setResult(RESULT_CANCELED);
setContentView(R.layout.activity_appwidget_configuration);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
image=(ImageView)findViewById(R.id.imageWidgetRed);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context= AppWidgetConfiguration.this;
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(getPackageName(),R.layout.appwidget);
views.setImageViewResource(R.id.imageWidget,R.mipmap.widgetred);
appWidgetManager.updateAppWidget(mAppWidgetId, views);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
});
}