使用foregroundservice 播放音乐 请给出代码举例
时间: 2024-10-23 21:04:09 浏览: 19
uCOS-II.rar_ucos 应用_ucosⅡ代码举例
ForegroundService 是 Android 中的一种服务,允许应用在后台持续运行而不被杀死,特别适合需要长时间执行的任务,比如播放音乐。以下是一个简单的例子,展示了如何使用 ForegroundService 来播放音乐:
首先,在 AndroidManifest.xml 文件中声明 Service 并设置 IntentFilter,以便用户可以在通知区域看到并操作该服务:
```xml
<service android:name=".MusicPlayerService"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
```
然后创建 MusicPlayerService 类:
```java
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.MediaPlayer;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class MusicPlayerService extends Service {
private MediaPlayer mediaPlayer;
private Notification notification;
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = new MediaPlayer();
// 初始化媒体播放器...
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String filePath = intent.getStringExtra("music_path");
// 设置音乐路径...
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
playMusic();
setupNotification();
return START_STICKY;
}
private void playMusic() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
private void setupNotification() {
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);
notification = new NotificationCompat.Builder(this)
.setContentTitle("音乐播放")
.setContentText("现在正在播放")
.setSmallIcon(R.drawable.ic_play)
.setContentIntent(pendingIntent)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
stopMedia();
}
private void stopMedia() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
// 清理通知...
if (notification != null) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.cancel(1);
}
}
}
```
要在主活动中启动这个服务,并传递音乐文件路径:
```java
Intent serviceIntent = new Intent(this, MusicPlayerService.class);
serviceIntent.putExtra("music_path", "file:///path/to/music.mp3"); // 替换为实际音乐路径
startService(serviceIntent);
```
注意,为了遵守 Android 的政策,你需要处理用户停止服务的情况,通常会在 Activity 中添加一个按钮或操作来暂停、继续播放或关闭服务。
阅读全文