我正在尝试用 java 创建一个在后台运行的简单服务。即使应用程序关闭,我也想在手机上播放歌曲。我阅读了一些文章并观看了教程,但当我关闭应用程序时,我的服务仍然停止。
1) 我更改了 list
<service
android:name="com.example.myapplication.ServiceSound"
android:exported="true"
android:enabled="true">
</service>
2) 我退回了START_STICKY
这是明显的
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.myapplication.ServiceSound"
android:exported="true"
android:enabled="true">
</service>
</application>
这就是服务
public class ServiceSound extends Service {
MediaPlayer player;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
这就是我在 MainActivity.java 中启动服务的方式
startService(new Intent(getBaseContext(),ServiceSound.class));
最佳答案
我认为你需要广播接收器。 所以现在 1- 创建广播接收器类并调用您的 Service 类。
public class MyBroadcaseReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,ServiceSound.class));
Log.e(TAG, "onReceive: BroadCast is started");
}
}
2-您的服务类定义了这一点
public static String str_receiver = "Your_Package_Name.receiver";
在startCommand上启动你的广播类
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.start();
return START_STICKY;
Intent intent1 = new Intent(this,MyBroadcaseReceiver.class);
sendBroadcast(intent1);
return START_STICKY;
}
现在在您的 MainActivity 类中创建一个用于广播的对象
私有(private)广播接收器广播接收器;
在onCreate()
内部定义对象
broadcastReceiver = new MyBroadcaseReceiver();
最后在MainActivity中调用onResume()
和onPause()
。
@Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(MyService.str_receiver));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
不要忘记在 list 文件中调用广播接收器
<receiver android:name=".MyBroadcaseReceiver"></receiver>
关于java - 我用 Java 创建了一个服务,但它不在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57864838/