从 Android 中的 AppWidget 发送公共广播

发布于 2024-09-06 04:37:37 字数 1213 浏览 6 评论 0原文

我有一个音乐播放器小部件,希望能够在按下不同按钮时发送广播。我想要做的是,当按下按钮时,小部件会向另一个 BroadcastReceiver 发送公共广播,以便它可以处理不同的操作。

在我的带有 BroadcastReceiver 的活动类中:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Constants.ACTION_NEXT)) {
      Log.d("RECEIVER", "ACTION_NEXT");
    }
  }
};

@Override
protected void onStart() {
  super.onStart();
  IntentFilter filter = new IntentFilter();

  //Widget actions
  filter.addAction(Constants.ACTION_NEXT);

  registerReceiver(broadcastReceiver, new IntentFilter(filter));
}

在我的小部件中:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
  RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Constants.ACTION_NEXT), 0);
  views.setOnClickPendingIntent(R.id.WidgetNextButton, pendingIntent);
  appWidgetManager.updateAppWidget(appWidgetId, views);
}

非常感谢任何帮助或其他解决方案!

编辑:忘记提及我的实际问题:BroadcastReceiver 永远不会收到广播

I have a widget for a music player and want to be able to send broadcasts when pushing the different buttons. What I want to do is when a button is pushed, the widget sends a public broadcast to another BroadcastReceiver so it can handle the different actions.

In my activity class with the BroadcastReceiver:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Constants.ACTION_NEXT)) {
      Log.d("RECEIVER", "ACTION_NEXT");
    }
  }
};

@Override
protected void onStart() {
  super.onStart();
  IntentFilter filter = new IntentFilter();

  //Widget actions
  filter.addAction(Constants.ACTION_NEXT);

  registerReceiver(broadcastReceiver, new IntentFilter(filter));
}

In my Widget:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
  RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Constants.ACTION_NEXT), 0);
  views.setOnClickPendingIntent(R.id.WidgetNextButton, pendingIntent);
  appWidgetManager.updateAppWidget(appWidgetId, views);
}

Any help or other solutions are very much appreciated!

EDIT: Forgot to mention my actual problem: The BroadcastReceiver never receive the broadcast

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文