我试图在Java中创建一个简单的服务,该服务将在后台运行。即使应用已关闭,我也想在手机上播放歌曲。我阅读了一些文章并观看了教程,但是当我关闭该应用程序时,我的服务仍然停止。
1)我更改了清单
<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));
答案 0 :(得分:0)
我认为您需要广播接收器。 所以现在 1-创建广播接收器类别并调用您的服务类别。
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 BroadcastReceiver broadcastReceiver;
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);
}
别忘了在清单文件中呼叫广播接收人
<receiver android:name=".MyBroadcaseReceiver"></receiver>