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

之前没有接触过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();
}



你可能感兴趣的:(Date,String,calendar,application,action,Components)