问题描述
我正在编写一个带有 Ionic 和 Capacitor 的音频播放器类型的应用程序,一切都很好。
设置:
问题:
- 无法从项目中的模块
MainActivity
中的app
访问capacitor-plugin-remote-audio.MyForegroundService
。这甚至可能吗?
说明问题的截图:
相关代码块
/* Used to build and start foreground service. */
public void startForegroundService()
{
Log.d(TAG,"Start foreground service.");
// Create notification default intent to open the MainActivity from Capacitor app when tapped.
Intent intent = new Intent(this,"What goes here to get the MainActivity");
PendingIntent pendingIntent = PendingIntent.getActivity(this,mainAppIntent,0);
createNotificationChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
.setongoing(true)
.setPriority(notificationmanager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.setShowWhen(false)
.setSmallIcon(android.R.drawable.ic_media_play) // Todo: fix this to use the app icon.
.setContentTitle("Content Title");
if (mainAppPendingIntent != null) {
builder.setContentIntent(mainAppPendingIntent);
}
addplayAndPauseButtons(builder);
startForeground(1,builder.build());
}
解决方法
启动服务时:
添加额外的包名称(可能不要硬编码,但无论如何):
// Start the foreground service + show required notification.
String packageName = getActivity().getPackageName();
Intent intent = new Intent(getContext(),MyForegroundService.class);
intent.putExtra(MyForegroundService.EXTRA_Top_Level_Package_Name,packageName);
intent.setAction(MyForegroundService.ACTION_START);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getContext().startForegroundService(intent);
} else {
getContext().startService(intent);
}
在服务中:
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
if(intent != null)
{
String action = intent.getAction();
switch (action)
{
case ACTION_START:
String packageName = intent.getExtras().get(EXTRA_Top_Level_Package_Name).toString();
startForegroundService(packageName);
break;
case ACTION_STOP:
stopForegroundService();
break;
}
}
return super.onStartCommand(intent,flags,startId);
}
启动方法
/* Used to build and start foreground service. */
public void startForegroundService(String packageName)
{
Log.d(TAG,"Start foreground service.");
// Create notification default intent to open the MainActivity from Capacitor app when tapped.
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
PendingIntent pendingIntent = PendingIntent.getActivity(this,intent,0);
createNotificationChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
.setOngoing(true)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.setShowWhen(false)
.setSmallIcon(android.R.drawable.ic_media_play) // TODO: fix this to use the app icon.
.setContentTitle("Content Title")
.setContentIntent(pendingIntent);
addPlayAndPauseButtons(builder);
startForeground(1,builder.build());
}
,
您正在尝试从另一个模块打开活动。检查此 answer 并可以解决您的问题。