接着AppWidget基础学习,今天是一个“进阶版”的小例子,用来检验一下自己的学习效果。于是就做了一个掷骰子的Widget。


方便大家观看,先截图如下:







需要注意的是在drawable文件夹下有几张图片,我是在网上下载的别人的素材,你也可以直接在图片素材下载链接,提取码是d47k。


下面就开始我们的学习之旅吧。


第一步:

是在res/目录下创建一个名为xml的文件夹(其实名字是随意的,不必拘泥与这一个名字),然后在里面创建一个appwidget_info.xml文件,其作用就是向系统进行声明。

<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minHeight="72dp"
    android:minWidth="294dp"
    android:updatePeriodMillis="86400000"
    android:initialLayout="@layout/app_widget_layout"
    >
</appwidget-provider>

第二步:

对布局界面进行设置,我的设置如下app_widget_layout.xml文件:

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

    <ImageView
        android:id="@+id/imageview_widget"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        />
    <Button
        android:id="@+id/button_widget"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="摇一摇"
        android:textColor="#6663c6"
        />

</LinearLayout>

第三步:

创建一个支撑widget的类,用来完成接下来的逻辑的操作,如下面的WidgetProvider.java.

package com.summer.mywidget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider{

    private static final String MY_UPDATE_ACTION="com.summer.APP_WIDGET_ACTION";

    /*
    *随机的获得一张图片的int值,为接下来的变换图片打基础
    */
    private static int getRandomPicture(){
        int[] pictureArray=new int[]{R.drawable.dice_1,R.drawable.dice_2,R.drawable.dice_3,
                R.drawable.dice_4,R.drawable.dice_5,R.drawable.dice_6};
        int RandomNumber=(int) ((Math.random()*100)%6);

        return pictureArray[RandomNumber];
    }

    /*
    *用于接收action,分支是区别于自定义ACTION和系统action的有效方式
    */
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String RESPONSEACTION=intent.getAction();
        Log.i("Summer", "------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+RESPONSEACTION);

        if(MY_UPDATE_ACTION.equals(RESPONSEACTION)){
            RemoteViews remoteViews=new RemoteViews(context.getPackageName(),R.layout.app_widget_layout);

            remoteViews.setImageViewResource(R.id.imageview_widget,getRandomPicture());

            AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(context);
            ComponentName componentName=new ComponentName(context,WidgetProvider.class);
            appWidgetManager.updateAppWidget(componentName, remoteViews);
        }else{
            super.onReceive(context, intent);
        }
    }

    /*
    *用一个循环的方式是为了应对桌面上添加了好几个这样的Widget的情形
    */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        // TODO Auto-generated method stub

        for(int i=0;i<appWidgetIds.length;i++){
            Intent intent=new Intent();
            intent.setAction(MY_UPDATE_ACTION);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(context, -1, intent, 0);

            RemoteViews remoteViews=new RemoteViews(context.getPackageName(),R.layout.app_widget_layout);
            remoteViews.setOnClickPendingIntent(R.id.button_widget,pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        // TODO Auto-generated method stub
        super.onDeleted(context, appWidgetIds);
        System.out.println("my app widget ----------------------------->>>>>>>onDeleted");
    }

    @Override
    public void onEnabled(Context context) {
        // TODO Auto-generated method stub
        System.out.println("my app widget ----------------------------->>>>>>>onEnabled");
        super.onEnabled(context);
    }

    @Override
    public void onDisabled(Context context) {
        // TODO Auto-generated method stub
        System.out.println("my app widget ----------------------------->>>>>>>onDisabled");
        super.onDisabled(context);
    }

}

第四步:

在清单文件Manifest.xml文件中进行相关项的声明。详如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.summer.mywidget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.summer.mywidget.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.summer.mywidget.WidgetProvider">
            <intent-filter >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <intent-filter >
                <action android:name="com.summer.APP_WIDGET_ACTION"></action>
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/appwidget_info">
            </meta-data>
        </receiver>
    </application>

</manifest>

第五步:

大功告成,运行一下代码,然后手工的进行app_Widget 的添加,然后你就可以拥有一款”骰子“咯。


总结:

这个小程序虽说是实现了,但是仍然不是比较复杂。需要对广播消息等知识有一定的了解。

改进方向:给每次的点击事件完成时添加动画效果,以获得更好地用户体验。(需要借助于RemoteViews内的相关的方法)。

代码中不可避免的会出现一些错误和不足之处,希望广大博友看到后予以指出,希望能和你们一起进步!

Android学习之AppWidget高级效果的更多相关文章

  1. 【转】 Pro Android学习笔记(四二):Fragment(7):切换效果

    目录(?)[-] 利用setTransition 利用setCustomAnimations 通过ObjectAnimator自定义动态效果 程序代码的编写 利用fragment transactio ...

  2. Android学习路线总结,绝对干货

    title: Android学习路线总结,绝对干货 tags: Android学习路线,Android学习资料,怎么学习android grammar_cjkRuby: true --- 一.前言 不 ...

  3. 一篇文章一张思维导图看懂Android学习最佳路线

    一篇文章一张思维导图看懂Android学习最佳路线 先上一张android开发知识点学习路线图思维导图 Android学习路线从4个阶段来对Android的学习过程做一个全面的分析:Android初级 ...

  4. 2015最新Android学习线路图

    Android是一个以Linux为基础的半开源操作系统,主要用于移动设备,由Google和开放手持设备联盟开发与领导.据2011年初数据显示仅正式上市两年的操作系统Android已经跃居全球最受欢迎的 ...

  5. Android学习路线指南

    看到这位大牛的博文,不禁得感概,我最近也遇到了很多问题,内心彷徨不堪,转载大牛这篇博文,是为了更好的勉励自己.原文地址在最后面. 前言 看到一篇文章中提到"最近几年国内的初级Android程 ...

  6. 一篇文章一张思维导图看懂Android学习最佳路线(转载)

    Android学习路线从4个阶段来对Android的学习过程做一个全面的分析:Android初级.中级.高级以及资深工程师.只针对Android应用开发,不针对Rom开发和逆向工程等.方便起见虚拟“小 ...

  7. (转)Android学习路线总结,绝对干货

    一.前言 不知不觉自己已经做了几年开发了,由记得刚出来工作的时候感觉自己能牛逼,现在回想起来感觉好无知.懂的越多的时候你才会发现懂的越少. 如果你的知识是一个圆,当你的圆越大时,圆外面的世界也就越大. ...

  8. Android学习路线总结,绝对干货(转)

    转自:https://www.cnblogs.com/yishaochu/p/5436094.html 一.前言 不知不觉自己已经做了几年开发了,由记得刚出来工作的时候感觉自己能牛逼,现在回想起来感觉 ...

  9. Android学习路线总结,绝对干货(转)

    title: Android学习路线总结,绝对干货tags: Android学习路线,Android学习资料,怎么学习androidgrammar_cjkRuby: true--- 一.前言 不知不觉 ...

随机推荐

  1. MongoDb进阶实践之六 MongoDB查询命令详述(补充)

    一.引言         上一篇文章我们已经介绍了MongoDB数据库的查询操作,但是并没有介绍全,随着自己的学习的深入,对查询又有了新的东西,决定补充进来.如果大家想看上一篇有关MongoDB查询的 ...

  2. box-sizing position

    box-sizing 属性 用于更改用于计算元素宽度和高度的默认的 CSS 盒子模型.可以使用此属性来模拟不正确支持CSS盒子模型规范的浏览器的行为. /* 关键字 值 */ box-sizing: ...

  3. window 2008 下 安装域管理并且控制禁用QQ和U盘

    场景需求下: 需求一:禁止普通用户使用USB.CD-ROM等驱动器防止病毒和资料外泄  需求二:并USB 键盘鼠标要可以使用 三:限制qq聊天工具的使用.这是公司真实环境需求.因此需要先模拟测试一下, ...

  4. Spring Boot 2.0系列文章(五):Spring Boot 2.0 项目源码结构预览

    关注我 转载请务必注明原创地址为:http://www.54tianzhisheng.cn/2018/04/15/springboot2_code/ 项目结构 结构分析: Spring-boot-pr ...

  5. JavaScript数据结构和算法----栈

    前言 栈是一种遵循后进先出(LIFO)原则的有序集合,新添加的或待删除的元素都保存在栈的末尾,称作栈顶,另外一端就叫栈底.在栈里,新元素都靠近栈顶,旧元素都接近栈底.可以想象桌上的一叠书,或者厨房里的 ...

  6. Hibernate更新数据(不用update也可以)

    在介绍hibernate的更新之前,我们先来看看session的两个方法.load和get方法:这两个方法是获取数据的根据对象的id值: 先看两段代码.load和get的方法都含有两个参数,前者是得到 ...

  7. 48. Rotate Image(中等)

    You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). ...

  8. linkList hashSet ArrayList IO 序列化 1.1.瞬态transient .字符编码表 Properties

      Day12 IO  序列化 .递归_递归的概念_注意事项 1.递归:方法的递归调用--它是一种方法调用的方式--方法可以调用其本身 2.注意事项: 1).递归必须要有一个"出口(结束的条 ...

  9. solr服务器搭建

    百度百科定义:Solr是一个独立的企业级搜索应用服务器,它对外提供类似于Web-service的API接口.用户可以通过http请求,向搜索引擎服务器提交一定格式的XML文件,生成索引:也可以通过Ht ...

  10. R语言中函数调试

    有时候会用R语言写一下简单的脚本处理函数,加入需要调试的话可以按照下面的步骤进行: fun <- function(x , y){ x + y x - y x * y x / y } debug ...