1
我有一個正常的應用程序與小部件(小部件是一個圖像按鈕)。點擊小部件時,我想調用MainActivity
中的方法或WidgetProvider
活動中的方法,或者將onClick
附加到小部件,該小部件在單擊它時會執行某些操作。我已閱讀文檔,但唯一發現的是如何使用小部件打開活動。Android Widget 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
。