AppWidget应用(二)---PendingIntent 之 getActivity

通过AppWidget应用(一)的介绍,我们已经知道如何创建一个在主界面上显示一个appWidget窗口,但这并不是我们的目的,我们需要做到程序与用户之间进行交互;下面来介绍下如何通过appWidget启动一个Activity。

一、在appWidget的布局文件中添加一个按钮

[html] view plaincopy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"   
  5.     android:orientation="vertical">  
  6.   
  7.     <TextView  
  8.         android:id="@+id/txtapp"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:background="#ffffff"  
  12.         android:text="test" >  
  13.     </TextView>  
  14.   
  15. <span style="background-color: rgb(255, 255, 255);"><span style="color:#ff0000;">    <Button  
  16.         android:id="@+id/btnSend"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:text="Send" >  
  20.     </Button></span></span>  
  21.   
  22. </LinearLayout>  

二、在appWidget上为按钮添加监听函数

[java] view plaincopy
 
  1. @Override  
  2.     public void onUpdate(Context context, AppWidgetManager appWidgetManager,  
  3.             int[] appWidgetIds) {  
  4.         // TODO Auto-generated method stub  
  5.         //遍历本程序启动的appWidget  
  6.         for (int i = 0; i < appWidgetIds.length; i++) {  
  7.             System.out.println("-----------appWidgetIds[] = " + appWidgetIds[i]);  
  8.             // 创建一个Intent对象  
  9.             Intent intent = new Intent(context, targetActivity.class); // 启动一个Activity  
  10.             // 创建一个PendingIntent对象 打开一个Activity  
  11.             PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,  
  12.                     intent, 0);  
  13.             RemoteViews remoteViews = new RemoteViews(context.getPackageName(),  
  14.                     R.layout.appwidgetlayout);  
  15.             // 为按钮绑定监听器  
  16.             remoteViews.setOnClickPendingIntent(R.id.btnSend, pendingIntent);  
  17.             // 更新App  
  18.             appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);  
  19.         }  
  20.         super.onUpdate(context, appWidgetManager, appWidgetIds);  
  21.     }  

targetActivity 就是点击按钮时要启动的Activity

按照AppWidget应用(一)中的方法启动后的appWidget效果如图:

最后是代码的地址:

点击打开链接

原文:http://blog.csdn.net/deng0zhaotai/article/details/10401489

原文地址:https://www.cnblogs.com/veins/p/3831775.html