Android之Widget组件

来源:互联网 发布:java executorservice 编辑:程序博客网 时间:2024/05/19 16:32

Widget组件可以放在桌面,提高程序的实用性。下面的代码演示了Widget的时钟组件的使用:

1.在Manifest文件中加入widget的recriver和一个service

<receiver android:name=".widget">            <intent-filter>                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />            </intent-filter>            <meta-data                android:name="android.appwidget.provider"                android:resource="@xml/widget_info" />        </receiver>        <service android:name=".TimerService"></service>
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.chase.cn.mywidget">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver android:name=".widget">            <intent-filter>                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />            </intent-filter>            <meta-data                android:name="android.appwidget.provider"                android:resource="@xml/widget_info" />        </receiver>        <service android:name=".TimerService"></service>    </application></manifest>

2.建立res文件夹下xml文件夹,并建立 widget_info.xml 如下:

<?xml version="1.0" encoding="utf-8"?><appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"    android:initialLayout="@layout/widget"    android:minHeight="40dp"    android:minWidth="180dp"    android:previewImage="@drawable/example_appwidget_preview"    android:updatePeriodMillis="0"></appwidget-provider>

3.在layout文件夹下建立文件widget.xml:这里面的textview就是我们动态改变的时钟。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="@dimen/widget_margin">    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_margin="8dp"        android:text="@string/appwidget_text"        android:textSize="24sp"/></RelativeLayout>

(P.S.以上步骤在AS中可以自动一键建立)

4.widget代码实现:

package com.chase.cn.mywidget;import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.Context;import android.content.Intent;/** * Implementation of App Widget functionality. */public class widget extends AppWidgetProvider {    @Override    //刷新widget时执行    //remoteViews和AppWidgetMananger    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {        // There may be multiple widgets active, so update all of them        super.onUpdate(context,appWidgetManager,appWidgetIds);    }    @Override    //第一个widget添加到屏幕上执行    public void onEnabled(Context context) {        // Enter relevant functionality for when the first widget is created        //启动Service        context.startService(new Intent(context,TimerService.class));    }    @Override    //最后一个widget被从屏幕移除执行    public void onDisabled(Context context) {        // Enter relevant functionality for when the last widget is disabled        //结束Service        context.stopService(new Intent(context,TimerService.class));    }    @Override    //widget被从屏幕移除了执行    public void onDeleted(Context context, int[] appWidgetIds) {        super.onDeleted(context, appWidgetIds);    }}

5.Service代码:

package com.chase.cn.mywidget;import android.annotation.SuppressLint;import android.app.Service;import android.appwidget.AppWidgetManager;import android.content.ComponentName;import android.content.Intent;import android.os.IBinder;import android.widget.RemoteViews;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;/** * Created by Chase on 2016/11/22. */public class TimerService extends Service {    private Timer timer;    @Override    public void onCreate() {        super.onCreate();        timer = new Timer();        timer.schedule(new MyTimerTask(), 0, 1000);    }    private final class MyTimerTask extends TimerTask{        @SuppressLint("SimpleDateFormat")        @Override        public void run() {            SimpleDateFormat sdf= new SimpleDateFormat("hh:mm:ss");            String time = sdf.format(new Date());            //获取Widgets管理器            AppWidgetManager widgetManager =AppWidgetManager.getInstance(getApplicationContext());            //widgetManager所操作的Widget对应的远程视图即当前Widget的layout文件            RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.widget);            remoteView.setTextViewText(R.id.tv, time);            //当点击Widgets时触发的事件            //remoteView.setOnClickPendingIntent(viewId, pendingIntent)            ComponentName componentName = new  ComponentName(getApplicationContext(),widget.class);            widgetManager.updateAppWidget(componentName, remoteView);        }    }    @Override    public void onDestroy() {        timer.cancel();        timer=null;        super.onDestroy();    }    @Override    public IBinder onBind(Intent intent) {        return null;    }}

或者Service这样也可以。

package com.chase.cn.mywidget;import android.app.Service;import android.appwidget.AppWidgetManager;import android.content.ComponentName;import android.content.Intent;import android.os.IBinder;import android.widget.RemoteViews;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;/** * Created by Chase on 2016/11/22. */public class TimerService extends Service {    private Timer timer;    //格式化日期的格式    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        super.onCreate();        timer = new Timer();        timer.schedule(new TimerTask() {            @Override            public void run() {                updateViews();            }        }, 0, 1000); //(new tesk,延迟,更新周期)    }    //定义一个update方法    private void updateViews() {        String time = sdf.format(new Date());        RemoteViews rv = new RemoteViews(getPackageName(), R.layout.widget);        rv.setTextViewText(R.id.tv,time);        AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext());        ComponentName cn = new ComponentName(getApplicationContext(),widget.class);        manager.updateAppWidget(cn,rv);    }    @Override    //销毁时倒计时停止    public void onDestroy() {        super.onDestroy();        timer = null;    }}

运行就ok了~

0 0