电池小工具没有工作,不会刷新电池的状态

时间:2014-09-11 23:16:31

标签: java android eclipse

我不知道,我做错了什么。 启动我的小部件后,我可以看到电池状态,但当我手动向telnet提供电源容量xx"时,它根本不刷新自身。命令。

MainActivity.java

public class MainActivity extends AppWidgetProvider
{
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
    {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);

        Intent received = context.getApplicationContext()
                .registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        String receivedAction = received.getAction();

        if (receivedAction.equals(Intent.ACTION_BATTERY_CHANGED))
        {
            int level = received.getIntExtra("level", 0);
            views.setTextViewText(R.id.TextView1, level + "%!");

            ComponentName appComponent = new ComponentName(context, MainActivity.class);
            appWidgetManager.getInstance(context).updateAppWidget(appComponent, views);
        }



    }
}

widgetxml.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="72dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="1800000"
    android:initialLayout="@layout/activity_main"
    >

</appwidget-provider>

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/TextView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

的AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

        <receiver android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"> </action>
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widgetxml" > </meta-data>
        </receiver>

    </application>
</manifest>

1 个答案:

答案 0 :(得分:0)

当您使用AppWidgetProvider时,您可以从任何活动更新窗口小部件,或者您可以从服务更新它。请查看以下链接,了解如何刷新小部件。

Programmatically update widget from activity/service/receiver

Force Android widget to update

另请查看vogella提供的精彩教程,解释有关小部件的所有内容。它还显示了如何通过单击或从任何服务更新小部件。

http://www.vogella.com/tutorials/AndroidWidgets/article.html