在Widget里获取系统时间改变的广播

本文介绍了如何在Android Widget中正确注册并接收系统TIME_TICK广播,实现定时更新Widget显示的时间。

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

之前没有接触过widget,widget本身就是一个广播。Intent.ACTION_TIME_TICK是一个系统广播,以下是官方介绍:

Broadcast Action: The current time has changed. Sent every minute. You can not receive this through components declared in manifests, only by exlicitly registering for it with Context.registerReceiver().

This is a protected intent that can only be sent by the system.

Constant Value: "android.intent.action.TIME_TICK"

文档里说的很明白了,这个广播不能在Manifest里注册。必须得在程序里进行注册。
在Widget的onEnable里写了如下注册:
 context.registerReceiver(this, new IntentFilter(Intent.ACTION_TIME_TICK));
在Widget的onReceiver里并没有收到广播,很是郁闷,后来发现Widget的context和Application的还不太一样,修改如下:

 context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_TIME_TICK));

在Widget的onReceiver就可以收到广播了,进行更新时间就可以了:

public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        String action = intent.getAction();
        
        if(action.equals(Intent.ACTION_TIME_TICK)){
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
            views.setTextViewText(R.id.time_text, getTime());
            ComponentName wd = new ComponentName( context, SystemDigitalClockWidget.class );
            AppWidgetManager.getInstance( context ).updateAppWidget( wd, views );
        }
        
        
    }


public  String getTime() {
        final Calendar date = Calendar.getInstance();
        int hour = date.get(Calendar.HOUR_OF_DAY);
        int minute = date.get(Calendar.MINUTE);
        return new StringBuffer().append(hour < 10 ? "0" + hour : hour).append(
                " : ").append(minute < 10 ? "0" + minute : minute).toString();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值