Android之Widget组件

本文介绍了如何在Android中创建和使用Widget组件,特别是时钟组件。通过在Manifest配置receiver和服务,建立widget_info.xml和widget.xml布局文件,以及编写相应的Widget和Service代码,可以实现在桌面展示动态更新的时钟。

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

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了~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值