android – 如何在按下widget按钮后启动活动?

this教程之后,我快速创建了一个简单的小部件,在主屏幕上显示当前时间:

我修改了代码,以便小部件也带有一个按钮.我的目标是在按下按钮后启动一个活动.
不幸的是,我真的不明白在哪里听按钮点击.这是否必须进入清单文件的广播接收器部分?

<!--  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?这是widget类代码:

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);
}   
最佳答案
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" />
   ....

转载注明原文:android – 如何在按下widget按钮后启动活动? - 代码日志