2014-01-09 69 views
1

我正在創建一個簡單的Android Widget,該按鈕會在應用程序中打開不同的活動。帶按鈕的Android Widget,刪除更新

public class ExampleAppWidgetProvider extends AppWidgetProvider { 

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
    final int N = appWidgetIds.length; 

    Log.i("ExampleWidget", "Updating widgets " + Arrays.asList(appWidgetIds)); 

    // Perform this loop procedure for each App Widget that belongs to this 
    // provider 
    for (int i = 0; i < N; i++) { 
     int appWidgetId = appWidgetIds[i]; 

     // Create an Intent to launch ExampleActivity 
     Intent intentForHome = new Intent(context, WidgetExampleActivity.class); 
     PendingIntent pendingIntentForHome = PendingIntent.getActivity(context, 0, intentForHome, 0); 
     // Get the layout for the App Widget and attach an on-click listener 
     // to the button 
     RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1); 
     views.setOnClickPendingIntent(R.id.button, pendingIntentForHome); 

     // Create an Intent to launch Second Activity 
     Intent intentForSecond = new Intent(context, SecondActivity.class); 
     PendingIntent pendingIntentForSecond = PendingIntent.getActivity(context, 0, intentForSecond, 0); 
     // Get the layout for the App Widget and attach an on-click listener 
     // to the button 
     views.setOnClickPendingIntent(R.id.button2, pendingIntentForSecond); 


     // Tell the AppWidgetManager to perform an update on the current app 
     // widget 
     appWidgetManager.updateAppWidget(appWidgetId, views); 
    } 
    } 
} 

這個工程並通過每個按鈕打開正確的活動。 但我只是想知道,什麼updatePeriodMillis是。我不需要Widget中的任何東西來更新,只需要按鈕來打開應用程序。我可以擺脫更新部分嗎?我不希望我的應用程序繼續更新小部件。

<?xml version="1.0" encoding="utf-8"?> 
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" 
    android:minWidth="294dp" 
    android:minHeight="72dp" 
    android:updatePeriodMillis="10000" 
    android:initialLayout="@layout/widget1"> 
</appwidget-provider> 

另外這是從一個Widget執行按鈕點擊的正確方法。我在一些教程中看到它的做法不同? 謝謝。

+0

Dublicate:http://stackoverflow.com/questions/5641134/how-to-disable-widget-updateperiodmillis –

回答

0

updatePeriod用於在某個時間間隔內刷新小部件。如果您不需要此設置,請將您的updatePeriodMillis設置爲0

+0

謝謝。 我也可以刪除這 代碼行appWidgetManager.updateAppWidget(appWidgetId,views); 此外,這是從Widget執行按鈕點擊的正確方法。我在一些教程中看到它的做法不同? – user3013243

0

This page描述瞭如何使用按鈕創建小部件。如果您不需要將窗口小部件修補程序updatePeriodMillis更新爲0.請注意,您不能使用頻率小於15分鐘的updatePeriodMillis,並且沒有關於刷新頻率的擔保(可能會有一些延遲)。如果你想刷新修復頻率使用報警或註冊到Intent.ACTION_TIME_TICK並自行管理

對於處理按鈕事件,這是正確的方法來做到這一點,因爲它是由Android頁面(上面)提到的。