android小部件通过按下小部件中的按钮来运行一个功能

时间:2012-05-23 01:49:18

标签: android widget

我想在我的小部件中添加一个按钮,以便它可以通过按下按钮来运行一个功能(更改APN并在小部件中显示已更改的消息)。事实上,自从我在一项活动中测试以来,该功能已经完成。有没有人知道怎么做?谢谢!

此致 Bill Chan

1 个答案:

答案 0 :(得分:1)

嗯,有几种方法。

例如,您可以在注册的AppWidgetProvider中创建类似的内容:

public static String ACTION_WIDGET_RECEIVER = "Action!";

@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget_layout);

        Intent active = new Intent(context, ThisClass.class);
        active.setAction(ACTION_WIDGET_RECEIVER);

        PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context,
                0, active, 0);

        remoteViews.setOnClickPendingIntent(R.id.button, actionPendingIntent);


        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
            final int appWidgetId = intent.getExtras().getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                this.onDeleted(context, new int[] { appWidgetId });
            }
        } else {
            if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
                doYourStuff();
            super.onReceive(context, intent);
        }
    }