实现时间Widget自动更新

本文介绍如何在Android应用中创建并实现一个简单的桌面小部件,包括XML布局定义、广播接收器和服务组件的设置,以及定时更新小部件显示的时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很简单的功能,废话不多说,直接上代码:

AndroidMainfest.xml:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <receiver android:name=".TimeWidget">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/time_widget_info" />
        </receiver>

        <service
            android:name=".TimeWidgetService">

        </service>
    </application>

</manifest>





</pre><p><br /></p><br />time_widge.xml:<p><pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#09C"
    android:padding="@dimen/widget_margin">

    <TextView
        android:id="@+id/counter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="00:00"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearance"/>
    <ImageView
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:src="@android:drawable/ic_media_play"/>

</LinearLayout>


</pre><p></p><pre>

time_widget_info.xml:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/time_widget"
    android:initialLayout="@layout/time_widget"
    android:minHeight="40dp"
    android:minWidth="110dp"
    android:previewImage="@drawable/example_appwidget_preview"
    android:resizeMode="horizontal|vertical"
    android:updatePeriodMillis="86400000"
    android:widgetCategory="home_screen|keyguard">

</appwidget-provider>




TimeWidget.java:

public class TimeWidget extends AppWidgetProvider {



    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        /*
         * 构造pendingIntent发广播,onReceive()根据收到的广播,更新
         */
        Intent intent = new Intent(context, TimeWidgetService.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
        RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.time_widget);
        rv.setOnClickPendingIntent(R.id.start, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, rv);
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled

    }
}



TimeWidgetService.java:

public class TimeWidgetService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.time_widget);
        final ComponentName componentName = new ComponentName(this, TimeWidget.class);
        final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);

        final Handler handler = new Handler();
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                SimpleDateFormat formatter = new SimpleDateFormat ("HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                remoteViews.setTextViewText(R.id.counter, str);
                appWidgetManager.updateAppWidget(componentName, remoteViews);
                handler.postDelayed(this, 500);// 150是延时时长
            }
        };
        handler.postDelayed(runnable, 500);// 打开定时器,执行操作
        return Service.START_STICKY;
    }
}






这样就实现了基本的功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值