I create a keyguard widget that has a button that upsate textview with Random number when clicking. it works properly on the home screen but on the lock screen (android 4.2.2) it(s button) works just when i add it to my lock screen widgets but when i turn screen off and return; it(s button) doesn't work !!
Widget.java
public class Widget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 50000);
}
class MyTime extends TimerTask {
RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
Context context;
public MyTime(Context context, AppWidgetManager appWidgetManager) {
this.appWidgetManager = appWidgetManager;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
thisWidget = new ComponentName(context, Widget.class);
this.context=context;
}
@Override
public void run() {
Intent configIntent = new Intent(context, WidgetReceive.class);
configIntent.setAction("updateTextView");
PendingIntent configPendingIntent = PendingIntent.getBroadcast(context, 0, configIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.button1, configPendingIntent);
remoteViews.setTextViewText(R.id.widget_textview, String.valueOf(new Random().nextInt(100)));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
}
WidgetReceive.java
public class WidgetReceive extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
ComponentName thisWidget = new ComponentName(context, Widget.class);
if(intent.getAction().equals("updateTextView")){
remoteViews.setTextViewText(R.id.widget_textview, String.valueOf(new Random().nextInt(100)));
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
}
}
AndroidManifest.xml
<receiver android:name=".Widget" 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/hello_widget_provider" />
</receiver>
<receiver android:name=".WidgetReceive">
<intent-filter>
<action android:name="updateTextView"/>
</intent-filter>
</receiver>
The problem might be that the following line
remoteViews.setOnClickPendingIntent(R.id.button1, configPendingIntent);
is missing from WidgetReceive.onReceive(...)
When updating an app widget with a RemoteViews
object, you must create all the contents of the widget, including the listeners, every time.