【发布时间】:2015-05-09 23:42:27
【问题描述】:
我有一个带有小部件的普通应用程序(小部件是一个图像按钮)。单击小部件时,我想调用来自MainActivity 的方法或来自WidgetProvider 活动的方法,或者将onClick 附加到小部件上,当我单击它时它会执行某些操作。我已经阅读了文档,但我发现的唯一内容是如何使用小部件打开活动。
我的 WidgetProvider 活动代码:
package ali.simpleflaslight;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.ImageButton;
import android.widget.RemoteViews;
public class WidgetProvider 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];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, MainActivity.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_layout);
views.setOnClickPendingIntent(R.id.imageButton, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public void someMethod() {
//I want this method called when imagebutton is pressed.
}
}
使用上面的代码,点击小部件只会显示我的MainActivity。
【问题讨论】: