AndroidApp/RecordingService.java

95 lines
3.3 KiB
Java
Raw Normal View History

2025-07-11 18:31:33 +08:00
package com.example.myapplication.Service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.example.myapplication.R;
public class RecordingService extends Service {
private static final String CHANNEL_ID = "recording_channel";
private static final int NOTIFICATION_ID = 1;
@RequiresApi(api = Build.VERSION_CODES.R)
@Override
public void onCreate() {
super.onCreate();
try {
createNotificationChannel();
// 启动前台服务必须5秒内调用startForeground
Notification notification = buildNotification("录音服务运行中");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Android 10+ 需要指定类型
startForeground(NOTIFICATION_ID, notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE);
} else {
// Android 8.0-9.0
startForeground(NOTIFICATION_ID, notification);
}
} catch (Exception e) {
Toast.makeText(this,"错误:"+e,Toast.LENGTH_LONG).show();
stopSelf();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"recording_channel",
"Recording Service",
NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
}
private Notification buildNotification(String text) {
// 确保图标有效R.drawable.ic_mic_on必须存在
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_mic_on)
.setContentTitle("录音服务")
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build();
}
public void updateNotification(String text) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
// 无权限时不显示通知(避免崩溃)
return;
}
}
NotificationManagerCompat.from(this)
.notify(NOTIFICATION_ID, buildNotification(text));
}
}