桌面小部件的简单开发步骤

AppWidgetProvider是Android中提供的用于实现桌面小部件的类,其本质是一个广播,继承自BroadcastReceiver
一 、定义桌面小部件
1 在layout下新建一个xml文件,命名为widget.xml



    

2 定义小部件配置信息
在res/xml下新建appwidget_provider_info.xml

    

initialLayout是指小工具所使用的初始化布局;minHeight,minWidth定义小工具的最小尺寸;updatePeriodMillis定义小工具的自动更新周期

3 定义小工具的实现类:该类继承AppWidgetProvider

public class MyAppWidgetProvider extends AppWidgetProvider {
public static final String TAG="MyAppWidgetProvider";
public static final String CLICK_ACTION="com.example.lihong.smallwidgetdemo.action.CLICK";

public MyAppWidgetProvider(){
    super();
}

@Override
public void onReceive(final Context context,Intent intent){
    super.onReceive(context,intent);
    Log.e(TAG,"onReceive:action="+intent.getAction());

    if(intent.getAction().equals(CLICK_ACTION)) {
        Toast.makeText(context, "Click it", Toast.LENGTH_SHORT).show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap srcBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_round);
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
                for (int i = 0; i < 37; i++) {
                    float degree = (i * 10) % 360;//10°旋转一次
                    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
                    remoteViews.setImageViewBitmap(R.id.imageView, rotateBitmap(context, srcBitmap, degree));
                    Intent intentClick = new Intent();
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intentClick, 0);
                    remoteViews.setOnClickPendingIntent(R.id.imageView, pendingIntent);
                    appWidgetManager.updateAppWidget(new ComponentName(context, MyAppWidgetProvider.class), remoteViews);
                    SystemClock.sleep(30);//休眠30毫秒后在进入下一次循环中
                }
            }
        }).start();
    }
}

/**
 * 每次桌面更新都会调用一次该方法
 * @param context
 * @param appWidgetManager
 * @param appWidgetIds 小部件的Id集合
 */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds){
    super.onUpdate(context,appWidgetManager,appWidgetIds);
    Log.i(TAG,"onUpdate");

    final int counter=appWidgetIds.length;
    Log.i(TAG,"counter="+counter);
    for(int i=0;i
        
        
        
            
            
        
    

上面由两个Action,一个是用于识别小部件的单击行为,第二个是作为小部件的表示必须存在的,是系统的规范

5 RemoteViews不同与普通得到View,无法直接向View那样通过setOnClickListener方法设置单击事件。RemoteViews的单击事件必须使用PendingIntent,如下代码:

     RemoteViews remoteViews=new RemoteViews(context.getPackageName(),R.layout.widget);
    //桌面小部件单击事件发送Intent广播
    Intent intent=new Intent();
    intent.setAction(CLICK_ACTION);//设置Action
    PendingIntent pendingIntent=PendingIntent.getBroadcast(context,0,intent,0);
    remoteViews.setOnClickPendingIntent(R.id.imageView,pendingIntent);//RemoteViews的点击事件

你可能感兴趣的:(安卓,android,小部件,RemoteView)