Following this , I quickly created a simple widget that displays the current time on the main screen:

I changed the code so the widget also comes with a button. My goal is to start the action after clicking the button. Unfortunately, I do not quite understand where to listen for the button click. Should this go to the broadcast section of the manifest file?
<receiver android:name=".WifiSSIDWidget" android:label="@string/app_name"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/wifi_ssid_widget_provider" /> </receiver>
Or is code more likely going to onUpdate ? Here is the widget class code:
public class HelloWidget extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Timer timer = new Timer(); timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000); } private class MyTime extends TimerTask { RemoteViews remoteViews; AppWidgetManager appWidgetManager; ComponentName thisWidget; DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault()); public MyTime(Context context, AppWidgetManager appWidgetManager) { this.appWidgetManager = appWidgetManager; remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); thisWidget = new ComponentName(context, HelloWidget.class); } @Override public void run() { remoteViews.setTextViewText(R.id.widget_textview, "TIME = " +format.format(new Date())); appWidgetManager.updateAppWidget(thisWidget, remoteViews); } } }
This calls the code that I want to call after clicking the button:
public void openWifiSettings() { final Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings"); intent.setComponent(cn); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }
source share