2013-05-20 195 views
4

this教程中,我迅速創建了一個簡單的小工具,顯示當前的時間在主屏幕上:我已經修改了代碼,這樣的小工具還帶有一個按鈕如何在按下按鈕按鈕後啓動活動?

enter image description here

。我的目標是啓動一個活動,一旦按鈕被按下。 不幸的是,我真的不明白在哪裏聽按鈕點擊。這是否必須進入清單文件的廣播接收器部分?

<!-- Broadcast Receiver --> 
<receiver android:name=".WifiSSIDWidget" android:label="@string/app_name"> 
    <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/> 
    </intent-filter> 
    <meta-data android:name="android.appwidget.provider" android:resource="@xml/wifi_ssid_widget_provider" /> 
</receiver>  

或者代碼寧願進入onUpdate?這裏的小部件類代碼:

public class HelloWidget extends AppWidgetProvider { 

    @Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 

     Timer timer = new Timer(); 
     timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000); 
    } 

    private class MyTime extends TimerTask { 
     RemoteViews remoteViews; 
     AppWidgetManager appWidgetManager; 
     ComponentName thisWidget; 
     DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault()); 

    public MyTime(Context context, AppWidgetManager appWidgetManager) { 
     this.appWidgetManager = appWidgetManager; 
     remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); 
     thisWidget = new ComponentName(context, HelloWidget.class); 
    } 

    @Override 
    public void run() { 
     remoteViews.setTextViewText(R.id.widget_textview, "TIME = " +format.format(new Date())); 
     appWidgetManager.updateAppWidget(thisWidget, remoteViews); 
    } 

    } 
} 

下面是我要的是點擊按鈕後調用的代碼:

public void openWifiSettings() { 
    final Intent intent = new Intent(Intent.ACTION_MAIN, null); 
    intent.addCategory(Intent.CATEGORY_LAUNCHER); 
    final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings"); 
    intent.setComponent(cn); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent); 
} 

回答

7
import android.app.PendingIntent; 
... 
public static final String ACTION_BUTTON1_CLICKED = "com.example.myapp.BUTTON1_CLICKED"; 

onUpdate以下添加到您的按鈕:

Intent intent = new Intent(ACTION_BUTTON1_CLICKED); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); 
remoteViews.setOnClickPendingIntent(R.id.button_1, pendingIntent); 

onReceive你的AppWidget

@Override 
public void onReceive(Context context, Intent intent) 
{ 
Log.d(TAG, "onReceive() " + intent.getAction()); 
super.onReceive(context, intent); 
... 
if (ACTION_BUTTON1_CLICKED.equals(intent.getAction())) 
{ 
// your code 
} 

還你的意圖添加到清單

<intent-filter> 
    <action android:name="com.example.myapp.BUTTON1_CLICKED" /> 
    .... 
+0

我應該在哪裏定義'ACTION_BUTTON1_CLICKED'? 'PendingIntent'也無法解析。您能否詳細闡述一下您的解決方案? – memyself

+0

我編輯了我的答案 –

+0

'remoteViews.setOnClickPendingIntent(R.id.button_1,pendingIntent);''''onUpdate'方法給了我一個錯誤:'無法解析'。 – memyself