【问题标题】:Android Widget Onclick Button or Method or Method from another Activity?Android Widget Onclick Button 或 Method 或 Method 来自另一个 Activity?
【发布时间】:2015-05-09 23:42:27
【问题描述】:

我有一个带有小部件的普通应用程序(小部件是一个图像按钮)。单击小部件时,我想调用来自MainActivity 的方法或来自WidgetProvider 活动的方法,或者将onClick 附加到小部件上,当我单击它时它会执行某些操作。我已经阅读了文档,但我发现的唯一内容是如何使用小部件打开活动。

我的 WidgetProvider 活动代码:

package ali.simpleflaslight;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.ImageButton;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider {

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

    // 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 intent = new Intent(context, MainActivity.class);
      PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 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.appwidget_layout);
      views.setOnClickPendingIntent(R.id.imageButton, pendingIntent);

      // Tell the AppWidgetManager to perform an update on the current app widget
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
  }
  public void someMethod() {
    //I want this method called when imagebutton is pressed.
  }
}

使用上面的代码,点击小部件只会显示我的MainActivity

【问题讨论】:

    标签: android methods widget


    【解决方案1】:

    &lt;receiver&gt;&lt;intent-filter&gt;标签的AndroidManifest.xml文件中添加一个动作:

    &lt;action android:name="MY_PACKAGE_NAME.WIDGET_BUTTON" /&gt;

    声明:

    public static String WIDGET_BUTTON = "MY_PACKAGE_NAME.WIDGET_BUTTON";

    onUpdate() 方法中添加与操作匹配的待处理意图:

    Intent intent = new Intent(WIDGET_BUTTON);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    views.setOnClickPendingIntent(R.id.MY_BUTTON_ID, pendingIntent);

    最后,在 onRecieve() 方法中:

     if (WIDGET_BUTTON.equals(intent.getAction())) {
       //Your Code
    
     }

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 1970-01-01
      • 2013-05-11
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      相关资源
      最近更新 更多