I have a flashlight app with widgets. The widget is used to turn the flashlight on and off and does not display the main activity or anything else. However, after a few hours, the widget does nothing. I mean, if you click on it, nothing will happen. I have two classes to accomplish this: Provider and Receiver .
Provider:
public class WidgetProvider extends AppWidgetProvider { @ Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Intent receiver = new Intent(context, FlashlightWidgetReceiver.class); receiver.setAction("COM_FLASHLIGHT"); receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_layout); views.setOnClickPendingIntent(R.id.imageButton, pendingIntent); appWidgetManager.updateAppWidget(appWidgetIds, views); } }
Receiver:
public class FlashlightWidgetReceiver extends BroadcastReceiver { private static boolean isLightOn = false; private static Camera camera; MediaPlayer mp;@ Override public void onReceive(Context context, Intent intent) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_layout); if (isLightOn) { views.setImageViewResource(R.id.imageButton, R.drawable.btn_switch_off); mp = MediaPlayer.create(context, R.raw.light_switch_off); } else { views.setImageViewResource(R.id.imageButton, R.drawable.btn_switch_on); mp = MediaPlayer.create(context, R.raw.light_switch_on); } mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @ Override public void onCompletion(MediaPlayer mp) {
Setup:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="40dp" android:minHeight="40dp" android:maxWidth="40dp" android:maxHeight="40dp" android:updatePeriodMillis="86400000" android:initialLayout="@layout/appwidget_layout" android:resizeMode="horizontal|vertical"> </appwidget-provider>
Update:. Reducing the refresh interval causes the widget to refresh more often, so if it gets stuck, it works again after 30 minutes, and then it can freeze again.
Update 2:. Changing the date will instantly freeze the widget until it is updated.
Update 3:. Changing the date somehow restarts the launcher and whenever the launcher starts, the widget freezes for 30 minutes.
source share