android開發之APP Widget

來源:互聯網
上載者:User

標籤:app widget   傳統型程式開發   

android開發之APP Widget本博文主要講述的android開發中的傳統型程式的開發--APP widget,主要用的是PendingIntent和RemoteViews。PendingIntent主要用來設定傳統型程式的相應方式。此對象可以有三種Intent方式,第一個是開始一個新的Activity,第二個是發送一個廣播,第三個是開始一個service。
RemoteViews的作用:因為傳統型程式和app程式不是屬於一個進程,不能通過正常的操作控制項的方式來操作。需要使用系統提供的RemoteViews對象來操作傳統型程式。在這個類中有設定APP Widget中控制項屬性的方法。
下面我們來看看代碼,在代碼中有分別包含了上述所說的PendingInetnt的兩種方式(part 1:開始一個新的Activity;part 2:發送一個廣播)和RemoteViews的使用方法:
主程式的Activity,MainActivity.java:
package com.example.appwidget;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;


public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}





appwidget傳統型程式的類AppWidgetProviderTest.java:

package com.example.appwidget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;


public class AppWidgetProviderTest extends AppWidgetProvider {


//自訂一個ACTION常量
private final String USER_ACTION = "com.example.appwiget.USER_ACTION";



//當APP widget執行個體被刪除時,會調用
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onDeleted(context, appWidgetIds);
System.out.println("onDeleted()");
}


//當最後一個app widget執行個體被刪除時,會調用
@Override
public void onDisabled(Context context) {
// TODO Auto-generated method stub
super.onDisabled(context);
System.out.println("onDisabled()");
}


//當第一個App widget執行個體被建立時,會調用
@Override
public void onEnabled(Context context) {
// TODO Auto-generated method stub
super.onEnabled(context);
System.out.println("onEnabled()");
}



//接收app收到的所有廣播事件
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("onReceive()");
//比較下,如果收到的廣播是USER_ACTION,則輸出資訊,且更新案頭控制項
if(USER_ACTION.equals(intent.getAction())){
System.out.println("onReceive --> " + USER_ACTION);
//獲得RemoteViews對象
RemoteViews remoteView = new RemoteViews(context.getPackageName(),R.layout.appwidget_provider);

//更新案頭TextView控制項的text
remoteView.setTextViewText(R.id.myText, "onReceive");

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName componentName = new ComponentName(context, AppWidgetProviderTest.class);

appWidgetManager.updateAppWidget(componentName, remoteView);

}else{
//調用父類的方法
super.onReceive(context, intent);
}
}


//在到達指定的更新時間之後或者向案頭添加App widget執行個體時,會調用此方法
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
System.out.println("onUpdate()");

//為每一個app widget執行個體綁定一個remoteViews監聽器,每建立的一個app widget執行個體都有一個對應的ID
for(int i = 0; i < appWidgetIds.length; i ++){

System.out.println("appWidgetIds -->" + appWidgetIds[i]);
//建立一個Intent對象
Intent intent = new Intent();

//part 1:pendingIntent用來開啟一個新的Activity
    /*intent.setClass(context, MainActivity.class);

    //使用getActivity方法建立一個pendingIntent對象,此對象用於跳轉Activity,將intent打包給pendingIntent
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    */
//end part1

//part 2:pendingIntent用來發送一個廣播
   //設定action
   intent.setAction(USER_ACTION);
   //使用getBroadcast()方法建立一個pendingIntent對象
   PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//end part2

//建立一個RemoteViews對象
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);

//RemoteViews對象將Button和pendingIntent綁定。通過pendingIntent獲得intent
remoteView.setOnClickPendingIntent(R.id.WidgetButton, pendingIntent);

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

}

}
}



主程式的主布局檔案main.xml:(程式的主介面)<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</RelativeLayout>


app widget的介面布局檔案appwidget_provider.xml:(在案頭看到的介面)<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
   <TextView 
       android:id="@+id/myText"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="welcome appwidget"
       android:background="#ff0000"
       />
   <Button 
       android:id="@+id/WidgetButton"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="Widget Button"
       />

</LinearLayout>


appwidget_provider的中繼資料的檔案appwidget_provider_info.xml:<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="180dp"
    android:minHeight="40dp"
    android:updatePeriodMillis="1000"
    android:initialLayout="@layout/appwidget_provider"    
    >
    
</appwidget-provider>


AndroidManifest.xml檔案:<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.appwidget"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.appwidget.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>  
        </activity>

        <receiver 
            android:name="com.example.appwidget.AppWidgetProviderTest">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <intent-filter ><!--自訂的過濾器  -->
                <action android:name="com.example.appwiget.USER_ACTION"/>
            </intent-filter>
            <meta-data 
                android:name="android.appwidget.provider"
                android:resource="@xml/appwidget_provider_info"/>
        </receiver>

    </application>

</manifest>


實現的效果如下:主程式介面:

app widget介面:

app widget需要在案頭上添加我們建立的app,才會在案頭上顯示出來。可以空白處長按,就會出來添加widget選項,選中我們的app既會在案頭顯示。
如上程式,點擊按鈕,就會發送廣播,並且修改widget中的TextView控制項的Text,點擊後的效果如下:

android開發之APP Widget

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.