您的位置:首页 > 移动开发 > Android开发

Android RemoteView的应用 三 新年倒计时通知栏

2017-04-10 16:55 459 查看
这个新年倒计时桌面小部件制作很简单,只是通过Timer不断刷新RemoteView就能做到

1. 在res/layout新建main作为部件的界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ddd">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/wordcup"
android:text="hello new year"
android:textSize="20dp"
android:textColor="#100f0f"/>
</LinearLayout>


在res/xml新建widget_provider配置部件界面的大小,刷新时间

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

</appwidget-provider>


3.部件实现类

public class WidetDemo extends AppWidgetProvider {
@Override
public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 60000);

}
private class MyTime extends TimerTask{

RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;

public MyTime(Context context,AppWidgetManager appWidgetManager){
this.appWidgetManager = appWidgetManager;
remoteViews = new RemoteViews(context.getPackageName(),R.layout.main);
thisWidget = new ComponentName(context,WidetDemo.class);

}

@Override
public void run() {

Date date = new Date();
Calendar calendar = new GregorianCalendar(2018,01,01);
long days = (((calendar.getTimeInMillis()-date.getTime())/1000)/86400);
remoteViews.setTextViewText(R.id.wordcup,"距离新年还有"+days+"天");
appWidgetManager.updateAppWidget(thisWidget,remoteViews);
}
}
}


4 . 注册文件

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


再见
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: