Android-Widget桌面应用小部件

官方文档中国版: https://developer.android.google.cn/guide/topics/appwidgets/index.html
这个网站是谷歌2016年底为中国开发者提供中国版,方便访问!

一.介绍

Android Widget是桌面应用小部件,可嵌入桌面,并可周期性更新Widget界面!     
例如在桌面的天气,日历类小工具就是Widget部件!

二.创建Widget广播接收器


public class ExampleAppWidgetProvider extends AppWidgetProvider {
    // onEnabled(Context)         widget可用触发
    // onDisabled(Context)        widget不可用触发
    // onDeleted(Context, int[])  widget被删除触发

    // widget更新触发
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {  
        final int N = appWidgetIds.length;  
        // Perform this loop procedure for each App Widget that belongs to this provider  
        for (int i=0; iint appWidgetId = appWidgetIds[i];

            // Create an Intent to launch ExampleActivity  
            Intent intent = new Intent(context, ExampleActivity.class);  
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener  
            // to the button  
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);  
            views.setOnClickPendingIntent(R.id.button, pendingIntent);  

            // Tell the AppWidgetManager to perform an update on the current app widget  
            appWidgetManager.updateAppWidget(appWidgetId, views);  
        }  
    }

    @Override  
    public void onReceive(Context context, Intent intent) {  
        AppWidgetManager mgr = AppWidgetManager.getInstance(context);  
        if (intent.getAction().equals(TOAST_ACTION)) {  
            int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,  
                AppWidgetManager.INVALID_APPWIDGET_ID);  
            int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0);  
            Toast.makeText(context, "Touched view " + viewIndex, Toast.LENGTH_SHORT).show();  
        }  
        super.onReceive(context, intent);       
        // Intent意图:
        // ACTION_APPWIDGET_UPDATE //处理更新
        // ACTION_APPWIDGET_DELETED // 处理删除
        // ACTION_APPWIDGET_ENABLED //可用
        // ACTION_APPWIDGET_DISABLED //不可用
        // ACTION_APPWIDGET_OPTIONS_CHANGED // 配置改变
    }
}

三.创建Widget基本信息(如布局等)

1.在AndroidManifest.xml中
  
      
          
      
     xml定义Widget基本信息(如布局等)


2.在res/xml/widget_info.xml中
  定义锁屏应用小部件的布局


3.widget布局xml

    .........
  
    ........
  

简书: http://www.jianshu.com/p/c997b9040401
CSDN博客: http://blog.csdn.net/qq_32115439/article/details/71598901
GitHub博客:http://lioil.win/2017/05/10/Android_Widget.html
Coding博客:http://c.lioil.win/2017/05/10/Android_Widget.html

你可能感兴趣的:(Android,Android笔记)