android 监听属性变化,小组件开发最佳实践(Android)

最后您还需要创建在清单中声明的ExampleAppWidgetProvider类。例如,如果您想要一个用于单击的按钮小组件,使用AppWidgetProvider实现的示例代码如下。

/*

* Copyright (C) 2008 The Android Open Source Project

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

public class ExampleAppWidgetProvider extends AppWidgetProvider {

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; i

int appWidgetId = appWidgetIds[i];

// Create an Intent to launch ExampleActivity

// Intent intent = new Intent(context, ExampleActivity.class);

Intent intent = new Intent();

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

// Get the layout for the App Widget and attach an on-click listener

// to the button,其中appwidget_provider_layout为创建的xml布局文件名称

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);

}

}

}

代码配置说明如下。

此AppWidgetProvider仅定义onUpdate()方法,并定义启动活动的PendingIntent,使用setOnClickPendingIntent(int,PendingIntent)将其添加到小组件的按钮上。

关于AppWidgetProvider的使用说明如下。

AppWidgetProvider回调通过onUpdate()方法。如果您的小组件需要接受用户的交互事件(此时您需要在此回调中注册事件处理程序),并且您的小组件不需要创建临时文件或数据库,也不需要执行其他清理的工作时,您无需关心除onUpdate()以外的生命周期回调。

说明 由于AppWidgetProvider是BroadcastReceiver的子类,因此不能保证您的进程在回调方法返回后仍能继续运行(有关广播生命周期的信息,请参见onUpdate()方法,通过在方法中启动服务来处理耗时操作。您可以从服务内部对小组件执行自己的更新,从而不必担心AppWidgetProvider会由于Application Not

Responding(ANR)而关闭。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值