天天看点

android widget 启动activity,android之appwidget(二)启动新activity

紧接上集,appwidget的周期函数对应的事件:

onUpdate:到达指定时间之后或者用户向桌面添加appwidget时候会调用这个方法。

onDelete:当appwidget被删除时,会调用这个方法。

onEnable:当一个appwidget第一次被创建,会调用这个方法。

onDisable:当最后一个appwidget实例被删除后,会调用这个方法。

onReveice:接受广播事件。

调试出来了么?

这集内容是如何与appwidget交互:

我们实现的功能是创建一个appwidget(为一个button),点击后,启动一个activity。

同样是新知识介绍:

1、我们的appwidget与我们对应的activity不是同一个进程,appwidget是homescreen中的一个进程。所以,我们不能直接对某一个控件进行事件监听,而是通过RemoteViews进行处理,而且我们也不能直接用intent进行启动activity,用pendingintent。

2、pendingintent:顾名思义,是还未确定的Intent。可以看做是对intent的一个包装,目的是对RemoteViews进行设置。形象点讲就是我们进程A中的intent想要在进程B中执行,需要pendingintent进行包装,然后添加到进程B中,进程B中遇到某个事件,然后执行intent。

创建pendingintent有三个方法:getActivity(context,requestCode,intent,flags)。getService()。getBroadcast()。

3、RemoteViews:即远程的views。他的作用是他所表示的对象运行在另外的进程中。

现在话不多说,果断代码:

1、我们在上集的appwidget.xml中(即桌面控件上加上一个Button)代码:

Java代码

android widget 启动activity,android之appwidget(二)启动新activity
android widget 启动activity,android之appwidget(二)启动新activity

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="测试按钮"

/>

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="测试按钮"

/>

2、我们在provider中的onUpdate方法中进行处理:

Java代码

android widget 启动activity,android之appwidget(二)启动新activity
android widget 启动activity,android之appwidget(二)启动新activity

for(inti=0;i

System.out.println(appWidgetIds[i]);

//新intent

Intent intent = newIntent(context,Appwidget2Activity.class);

//创建一个pendingIntent。另外两个参数以后再讲。

PendingIntent pendingIntent = PendingIntent.getActivity(

context, 0, intent,0);

//创建一个remoteViews。

RemoteViews remoteViews = newRemoteViews(

context.getPackageName(), R.layout.appwidget);

//绑定处理器,表示控件单击后,会启动pendingIntent。

remoteViews.setOnClickPendingIntent(R.id.button, pendingIntent);

appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);

}

for(int i= 0;i

System.out.println(appWidgetIds[i]);

//新intent

Intent intent = new Intent(context,Appwidget2Activity.class);

//创建一个pendingIntent。另外两个参数以后再讲。

PendingIntent pendingIntent = PendingIntent.getActivity(

context, 0, intent, 0);

//创建一个remoteViews。

RemoteViews remoteViews = new RemoteViews(

context.getPackageName(), R.layout.appwidget);

//绑定处理器,表示控件单击后,会启动pendingIntent。

remoteViews.setOnClickPendingIntent(R.id.button, pendingIntent);

appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);

}

因为我们可能有多个appwidget,所以要遍历。创建一个intent,与要启动的activity关联起来,然后根据该intent创建一个pendingintent。然后根据appwidget.xml创建一个remoteViews,然后对该views中的一个控件进行pendingintent绑定。