android开发之widget的研究(OPWidget关于海贼王的小插件)(上)

2 篇文章 0 订阅
2 篇文章 0 订阅


以前学习android的时候,一直对widget如何设计挺感兴趣的,但是由于种种不是原因的原因,一直耽搁着没去研究,实在是不应该啊!最近,终于花了点时间把widget给研究了一遍,而opwidget就是我最后的研究成果!o(∩_∩)o (在最后面会附上源码)

PS:因为我是OP的忠实粉丝,所以demo里面很多图片都是海贼王的,呵呵!

热爱android+热爱OP =OPwidget !



废话不多说,直入正题!


一、Widget的一些基本知识:
 ①每个widget其实就是一个BroadcastReceiver,因为写widget时需要写一个widget类去继承AppWidgetProvider, 而AppWidgetProvider类继承于BroadcastReceiver。


widgetxml文件来描述,该xml文件放在 res/xml目录下。


③应用程序与widge的区别:
应用程序更新组件时,先获取对象,再直接对组件进行更新。
widget无法直接获取widget组件的对象,需要用 RemoteViews作为代理来更新


④widget并不支持所有的Android组件的更新
支持的布局类组件类(3个):Framelayout,LinearLayout,RelativeLayout
支持的可视化组件类(7个):ImageButton,Button,ImageView,ProgressBar,TextView,AnalogClock(钟),Chronometer(计时器)


每个单元格占74px,

widget的单元格计算 : (单元格数*74)-2     单位推荐使用dip/dp

因为像素计算会带来一定的偏差,所以这里要减2


这里顺便说下像素单位的简介,毕竟做android开发,这块还是必须要了解的!
px(pixels--像素)
dip(device independent pixels--设备独立像素) 与密度无关的像素,一般不使用px,而推荐使用dip
sp (scaled pixels--放大像素)  与刻度无关的的像素,主要用于字体显示!
pt(磅)=1/72 英寸 = 2.22sp


二、开发widget

①建立widget类,继承AppWidgetProvider类

AppWidgetProvider方法的介绍:<摘自http://blog.csdn.net/iefreer/article/details/4626274>

onUpdate(Context, AppWidgetManager, int[])
这个方法调用来间隔性的更新App Widget,间隔时间用AppWidgetProviderInfo 里的updatePeriodMillis属性定义(参见添加AppWidgetProviderInfo元数据)。这个方法也会在用户添加App Widget时被调用,因此它应该执行基础的设置,比如为视图定义事件处理器并启动一个临时的服务Service,如果需要的话。但是,如果你已经声明了一个配置活动,这个方法在用户添加App Widget时将不会被调用,而只在后续更新时被调用。配置活动应该在配置完成时负责执行第一次更新。(参见下面的创建一个App Widget配置活动Creating an App Widget Configuration Activity。)

onDeleted(Context, int[])
当App Widget从宿主中删除时被调用。

onEnabled(Context)
当一个App Widget实例第一次创建时被调用。比如,如果用户添加两个你的App Widget实例,只在第一次被调用。如果你需要打开一个新的数据库或者执行其他对于所有的App Widget实例只需要发生一次的设置,那么这里是完成这个工作的好地方。

onDisabled(Context)
当你的App Widget的最后一个实例被从宿主中删除时被调用。你应该在onEnabled(Context)中做一些清理工作,比如删除一个临时的数据库。

onReceive(Context, Intent)
这个接收到每个广播时都会被调用,而且在上面的回调函数之前。你通常不需要实现这个方法,因为缺省的AppWidgetProvider 实现过滤所有App Widget 广播并恰当的调用上述方法。

package ace.widget.mybattery;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;

public class BatteryWidget extends AppWidgetProvider {
	private Context context;
	private Timer timer;
	private AppWidgetManager appWidgetManager;
	private int[] appWidgetIds;
	private RemoteViews remoteViews;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		this.context = context;
		this.appWidgetManager = appWidgetManager;
		this.appWidgetIds = appWidgetIds;
		timer = new Timer();
		timer.scheduleAtFixedRate(timerTask, 0, 1000);
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int n = appWidgetIds.length;
			for (int i = 0; i < n; i++) {
				int appWidgetId = appWidgetIds[i];
				DateFormat df = new SimpleDateFormat("yyyy.MM.dd/HH:mm:ss E");
				remoteViews.setTextViewText(R.id.tv, df.format(new Date()));
				appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
			}
		}
	};

	TimerTask timerTask = new TimerTask() {
		@Override
		public void run() {
			handler.sendEmptyMessage(0);
		}
	};
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);
		if(timer != null){
			timer.cancel();
		}
	}
}


②res/xml目录下定义一个widget的描述文件

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


PS:看网上资料说,在SDK1.5之后,android:updatePeriodMillis就没用了,不会再定时更新appWidget了,所以这里的值设置多少都不会有影响,但是最好设置大一点, 防止万一又有效了,更新的太频繁会不好。

具体widget的样式放在res/layout/main.xml文件下,所以这里用android:initLayout="@layout/main"

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mRelativeLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/imageView_background"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:src="@drawable/white_bg" />

    <RelativeLayout
        android:id="@+id/mRelativeLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="142dp"
            android:layout_centerInParent="true"
            android:src="@drawable/op1"
             />

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imageView"
            android:layout_centerInParent="true"
            android:background="@drawable/background"
            android:text="Welcome 2 Android "
            android:textColor="@android:color/white"
            android:textSize="14sp"
            android:textStyle="bold" />
    </RelativeLayout>

</FrameLayout>


③在AndroidManifest.xml文件中定义一个receiver,以便系统和widget通信

 <receiver
            android:label="@string/app_name"
            android:name=".OPWidget" >
            <intent-filter >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/opwidget_layout" />
  </receiver>

<receiver>元素需要android:name属性,它指定了App Widget使用的AppWidgetProvider 。

<intent-filter> 元素必须包括一个含有android:name属性的<action>元素。该元素指定AppWidgetProvider接受ACTION_APPWIDGET_UPDATE 广播。这是唯一你必须显式声明的广播。当需要的时候,AppWidgetManager 会自动发送所有其他App Widget广播给AppWidgetProvider。

<meta-data> 元素指定了AppWidgetProviderInfo 资源并需要以下属性:

·         android:name – 指定元数据名称。

·         android:resource – 指定AppWidgetProviderInfo 资源路径。

做到这里一个widget的基本雏形就出来了,运行一下吧!o(∩_∩)o 


④点击桌面的widget,弹出一个Activity(DescActivity)

这里需要在widget类中onUpdate方法进行相关的设置,在最下面插入如下代码

// 设置widget点击事件
		remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
		Intent intent = new Intent(context, SettingActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				intent, 0);
		remoteViews.setOnClickPendingIntent(R.id.imageView, pendingIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

这里既然提到了PendingIntent类,就写一下相关资料上对他的说明。

intent英文意思是意图,pending表示即将发生或来临的事情。

PendingIntent其实就是一个Intent的描述,我们可以把这个描述交给别的程序,别的程序根据这个描述在后面的别的时间做你安排做的事情。

PendingIntent的四个参数:

FLAG_CANCEL_CURRENT:如果该PendingIntent已经存在,则在生成新的之前取消当前的。

FLAG_NO_CREATE:如果该PendingIntent不存在,直接返回null而不是创建一个PendingIntent.

FLAG_ONE_SHOT:该PendingIntent只能用一次,在send()方法执行后,自动取消。

FLAG_UPDATE_CURRENT:如果该PendingIntent已经存在,则用新传入的Intent更新当前的数据。


DescActivity:

package ace.widget.myopwidget;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ViewSwitcher.ViewFactory;

public class DescActivity extends Activity implements OnItemSelectedListener,
		ViewFactory {
	private ImageSwitcher is;
	private Gallery gallery;
	private int tempImageID;

	private Integer[] mThumbIds = { R.drawable.opicon, R.drawable.op1,
			R.drawable.op2, R.drawable.op3, R.drawable.op4, R.drawable.op5,
			R.drawable.op6, R.drawable.op7, R.drawable.op8, R.drawable.op9,
			R.drawable.op10, R.drawable.op11, R.drawable.op12, R.drawable.op13,
			R.drawable.op14, R.drawable.op15, R.drawable.op16, R.drawable.op17,
			R.drawable.op18, R.drawable.op19, R.drawable.op20, R.drawable.op21,
			R.drawable.op22, R.drawable.op23, R.drawable.op24, R.drawable.op25 };

	private Integer[] mImageIds = mThumbIds;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_xml);
		System.out.println(getWidgetId());
		is = (ImageSwitcher) findViewById(R.id.switcher);
		is.setFactory(this);

		is.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		is.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));

		gallery = (Gallery) findViewById(R.id.gallery);
		gallery.setAdapter(new ImageAdapter(this));
		gallery.setOnItemSelectedListener(this);
	}

	@Override
	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		i.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setDialog();
			}
		});
		return i;
	}

	public class ImageAdapter extends BaseAdapter {
		public ImageAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return mThumbIds.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);
			i.setImageResource(mThumbIds[position]);
			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			i.setBackgroundResource(R.drawable.e);
			return i;
		}

		private Context mContext;

	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		is.setImageResource(mImageIds[position]);
		tempImageID = mImageIds[position];
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	private void setDialog() {
		AlertDialog.Builder builder = new Builder(DescActivity.this);
		builder.setMessage("确定将这张图片显示到桌面插件上?");
		builder.setTitle("友情提示ByAce:");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				System.out.println(tempImageID);
				dialog.dismiss();
				DescActivity.this.finish();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

}

activity_xml.xml

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

        <ImageSwitcher
            android:id="@+id/switcher"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true" />

        <Gallery
            android:id="@+id/gallery"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:background="#55000000"
            android:gravity="center_vertical"
            android:spacing="16dp" />
    </RelativeLayout>

</LinearLayout>


效果图:

         点击widget进入DescActivity       


④完成DescActivity与widget的一个信息的交互,使widget的图片更换

具体实现逻辑:首先点击widget时,传递给DescActivity当前widget的id

(修改widget的onUpdate方法如下)

@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		this.context = context;
		mAppWidgetManager = appWidgetManager;
		mAppWidgetIds = appWidgetIds;
		
		mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
		// 一般情况下 每次拉一个插件到桌面,n都为1
		int n = appWidgetIds.length;
		for (int i = 0; i < n; i++) {
			Intent intent = new Intent(context, DescActivity.class);
			Bundle bundle = new Bundle();
			int widgetId = appWidgetIds[i];
			bundle.putInt("op_widget_id", widgetId);
			intent.putExtras(bundle);
			// 定时器
			Timer timer = new Timer();
			timer.schedule(timerTask, 0,1000);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			mRemoteViews.setOnClickPendingIntent(R.id.imageView, pendingIntent);
			appWidgetManager.updateAppWidget(appWidgetIds, mRemoteViews);
		}
	}
然后在DescActivity中添加如下方法代码

private void setIntent() {
		Intent intent = new Intent();
		intent.setAction("ace.widget.update");
		Bundle bundle = new Bundle();
		bundle.putInt("ivID", tempImageID);
		bundle.putInt("widgetID", getWidgetId());
		intent.putExtras(bundle);
		this.sendBroadcast(intent);
	}

	/** 获取widget的id */
	private int getWidgetId() {
		Intent getWidgetIdIntent = getIntent();
		Bundle bundle = getWidgetIdIntent.getExtras();
		int widgetID = bundle.getInt("op_widget_id");
		System.out.println("获取的id:" + widgetID);
		return widgetID;
	}

这里因为等会要传递信息给widget,而widget本身是一个BroadcasstReceiver,所以这里设置一个action,然后通过sendBroadcast方法通知widget,接着在Androidmanifest.xml进行如下的修改

 <receiver
            android:label="@string/app_name"
            android:name=".OPWidget" >
            <intent-filter >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="ace.widget.update" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/opwidget_layout" />
        </receiver>

然后在DescActivity的设置dialog的点击确定事件里面进行如下修改:

builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				setIntent();
				dialog.dismiss();
				DescActivity.this.finish();
			}
		});
最后在widget中重写onReceive方法

@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals("ace.widget.update")) {
			Bundle bundle = intent.getExtras();
			int ivID = bundle.getInt("ivID");
			int widgetID = bundle.getInt("widgetID");
			RemoteViews views = new RemoteViews(context.getPackageName(),
					R.layout.main);
			AppWidgetManager manager = AppWidgetManager.getInstance(context);
			views.setImageViewResource(R.id.imageView, ivID);
			manager.updateAppWidget(widgetID, views);
		}
		super.onReceive(context, intent);
	}

附上的代码应该还需要稍微修改下,因为我剪切的代码是最后完整版上的。嘿嘿。。。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值