如何将消息发送到Android中的其他应用?

时间:2019-07-15 12:39:25

标签: android background-music

我想在我的应用程序中对音乐控制器进行编程,这样我就可以从另一个内置音乐应用程序播放/暂停我的播放列表中的nextSong和previousSong。我已经看到了使用广播向所有音乐播放器发送消息以开始播放音乐的解决方案。问题是,音乐开始在我安装的三个不同的音乐播放器上播放。有谁知道该用什么而不是sendBroadcast,以便该消息仅发送到我想要的应用程序?

我在互联网上找到了这个解决方案。它使用sendBroadcast()函数。该消息广播到我不需要的每个音乐播放器。我希望仅将其发送到一个特定的应用程序

long eventTime = SystemClock.uptimeMillis();

/*NEXT*/
Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent downEvent = new KeyEvent(eventTime, eventTime, 
    KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS, 0);
downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
sendBroadcast(downIntent, null);

Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent upEvent = new KeyEvent(eventTime, eventTime, 
    KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS, 0);
upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
sendBroadcast(upIntent, null);

1 个答案:

答案 0 :(得分:1)

首先,在清单文件中声明接收方:

<receiver android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
    <intent-filter>
      <action android:name="com.pkg.perform.Ruby" />
    </intent-filter>

就我而言,我是这样使用的:

   final Intent intent=new Intent();
intent.setAction("com.pkg.perform.Ruby");
intent.putExtra("KeyName","code1id");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setComponent(  
    new ComponentName("com.pkg.AppB","com.pkg.AppB.MyBroadcastReceiver"));  
sendBroadcast(intent);