您的位置:首页 > 移动开发 > Android开发

定制android桌面系统

2017-11-27 17:22 330 查看
     最近项目用到桌面定制,于是研究了AppWidgetProvider,话不多说,直接进入正题.

其实打开AppWidgetProvider源码我们会发现,他是继承于broadcastReceiver的广播接收器,其中会定义一个onUpdate的方法,该方法会在桌面加载或者更新的时候调用,里面定义了三个参数,分别是context,appWidgetManager和appWidgetIds,其中appWidgetsIds是桌面ID.而且此时我们需要开启一个服务,定时的更新桌面按钮触发事件.

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.d(TAG, " ------ onUpdate(): appWidgetIds.length=" + appWidgetIds.length);

// 每次 widget 被创建时,对应的将widget的id添加到set中
for (int appWidgetId : appWidgetIds) {
idsSet.add(Integer.valueOf(appWidgetId));
}
prtSet(context);

// 解决CashierWidgetProvider没有定时刷新问题(不刷新则不会变化layout 已经按钮触发事件)
Log.d(TAG, " ------ onUpdate(): CashierWidgetService");
Intent intent = new Intent(context, MyWidgetService.class);
PendingIntent refreshIntent = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC, 0, 1000, refreshIntent);
context.startService(intent);
}
在onReceive里会接收服务发来的广播,此时我们需要更新桌面,并对刷新按钮的触发事件,如果广播接收的action是Intent.CATEGORY_ALTERNATIVE
此时可根据data.getSchemeSpecificPart()做相应的点击事件
@Override
public void onReceive(Context context, Intent intent) {
if (context == null) {
return;
}
final String action = intent.getAction();
Log.d(TAG, " ------ OnReceive:Action: " + action);
if (ACTION_UPDATE_ALL.equals(action)) {
// “更新”广播,当覆盖安装时:AppWidgetManager.getInstance(context)会报空指针
updateAllAppWidgets(context, AppWidgetManager.getInstance(context), idsSet);

} else if (intent.hasCategory(Intent.CATEGORY_ALTERNATIVE)) {
// “按钮点击”广播
Uri data = intent.getData();
int clickId = Integer.parseInt(data.getSchemeSpecificPart());
Log.d(TAG, " ------ OnReceive:clickId: " + clickId);
switch (clickId) {
case REQUEST_CLICK_RL0_EVENT:
startPetApp(context, Activity_One.class);
break;
case REQUEST_CLICK_RL1_EVENT:
startPetApp(context, Activity_Two.class);

break;
case REQUEST_CLICK_RL2_EVENT:
startPetApp(context, Activity_One.class);
break;
case REQUEST_CLICK_RL3_EVENT:
startPetApp(context, Activity_Two.class);

break;
case REQUEST_CLICK_RL4_EVENT:
startPetApp(context, Activity_One.class);

break;
case REQUEST_CLICK_RL5_EVENT:
startPetApp(context, Activity_Two.class);

break;
case REQUEST_CLICK_RL6_EVENT:
startPetApp(context, Activity_One.class);

break;

default:
break;
}
}

super.onReceive(context, intent);
}
源码地址   https://github.com/kyrieLiu/petWidget1.git 运行demo方法:运行后长按桌面,点击小组件,找到桌面dmeo,把它拖到桌面上来,然后可以查看效果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: