我创建了一个键盘锁小部件,其中包含一个按钮,可在单击时使用随机数提升textview。它在主屏幕上正常工作,但在锁定屏幕上(android 4.2.2)它(s按钮)工作时,我将它添加到我的锁屏小部件,但当我关闭屏幕并返回;它(s按钮)不起作用!!
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>
答案 0 :(得分:0)
问题可能是以下一行
remoteViews.setOnClickPendingIntent(R.id.button1, configPendingIntent);
WidgetReceive.onReceive(...)
缺少
使用RemoteViews
对象更新应用小部件时,您必须每次都创建小部件的所有内容,包括侦听器。