以下是一个示例代码,用于在Android前台服务中播放振动:
public class VibrationService extends Service {
private static final int NOTIFICATION_ID = 1;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(NOTIFICATION_ID, createNotification());
startVibration();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
stopVibration();
}
private void startVibration() {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
long[] pattern = {0, 1000, 1000}; // 振动间隔:0ms延迟、1000ms振动、1000ms暂停
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
VibrationEffect vibrationEffect = VibrationEffect.createWaveform(pattern, 0);
vibrator.vibrate(vibrationEffect);
} else {
vibrator.vibrate(pattern, 0);
}
}
}
private void stopVibration() {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
vibrator.cancel();
}
}
private Notification createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Foreground Service")
.setContentText("正在播放振动")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("channel_id", "Foreground Service", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
return builder.build();
}
}
Intent intent = new Intent(context, VibrationService.class);
ContextCompat.startForegroundService(context, intent);
注意:在AndroidManifest.xml文件中添加了
权限声明,以获取振动权限。