OnUpdate NEVER调用 - Android Widget

Jod*_*ron 6 android widget onupdate

我一直在关注各种Widget教程,例如教程和教程

我已经尝试将他们的代码调整到我的目的,我尝试了直接复制粘贴.似乎无论我做什么,我的小部件都不会更新.当它放在主屏幕上时,文本将保留为创建它的静态文本.我需要这个应用程序才能更新4个TextViews,它将包含在布局中.

下面的代码主要是从其中一个教程中复制而来.我已经尝试过调试onUpdate方法,但是破解点似乎永远不会受到影响.

任何帮助将不胜感激.

编辑:我恢复了这个小部件的一个更简单的版本,我之前尝试过我的努力,并用更简单的小部件的代码替换下面的代码.我将CommonsWare建议的更改发送到我的清单.不幸的是问题仍然存在

我的主要.java文件看起来像这样:

public class NetStatWidget extends AppWidgetProvider 
{

public void onUpdate(Context context, AppWidgetManager manager, int[] appWidgetIds)
{   
    ComponentName thisWidget = new ComponentName(context, NetStatWidget.class);
    int[] widgetId = manager.getAppWidgetIds(thisWidget);

    RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.appwidget);
    remoteView.setTextViewText(R.id.textView0, "Hello");
    manager.updateAppWidget(widgetId, remoteView);
}

}
Run Code Online (Sandbox Code Playgroud)

我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.stat"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >


            <receiver android:name="NetStatWidget" >
                <intent-filter>
                    <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                </intent-filter>
                <meta-data 
                    android:name="android.appwidget.provider"
                    android:resource="@xml/providerinfo" />
            </receiver>

    </application>

</manifest>
Run Code Online (Sandbox Code Playgroud)

我的Widget提供商信息:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/main"
android:minWidth="146dip"
    android:minHeight="72dip"
    android:updatePeriodMillis="10000">
Run Code Online (Sandbox Code Playgroud)

Com*_*are 7

你的清单是错的.你声称你有一个network.widget.AppWidgetProvider课程,而AFAIK,你没有.你有一个奇怪的名字network.widget.NetworkWidgetActivity.您需要在元素中使用<receiver>.

也:

  • 更换this.getApplicationContext()getApplicationContext()使用this

  • 除非你打算在服务中做更严肃的工作(数据库I/O,网络I/O等),否则考虑将所有逻辑移入onUpdate()并删除服务,因为它并不是真的在这里买了很多(和如果你要保持服务,切换到IntentService,摆脱stopSelf()因为这是为您处理)

  • 当您要求进行10秒更新时,最低有效时间updatePeriodMillis为30分钟 - 在调试时请记住这一点

  • int[] widgetId 好像没用了 NetworkWidgetActivity

  • onStart()在一个Service已被弃用了几年; 使用onStartCommand()替代

  • @Jodron:"我认为一旦放置小部件"textView0"应该读为"Hello",我是错误的吗?" - 好吧,在一秒左右的时间内,假设在`res/layout/appwidget.xml`中有一个名为`@ + id/textView0`的`TextView`.虽然你在那里列出的代码将无法编译,因为没有`widgetId`.考虑暂时切换到带有`ComponentName`的`updateAppWidget()`版本,这样你就不会迷失在app widget ID中. (2认同)