最近一个语音项目需要唤醒功能,发现语音在应用进入后台一段时间,麦克风占用的那个红色警示还在,但是确监听不到麦克风的数据,只能百度一下坑在哪里,找到方法,发送前台通知完美解决。
首先我们写个service
/**
* 前台service调整 我要让应用在后台 也能够监听麦克风
*/
public class NotificationService extends Service {
private static final String TAG = "NotificationService";
private NotificationManager notificationManager;
//通知的标识号。
private int NOTIFICATION = 999;
public static NotificationService service;//启动service时候我们记录这service方便移除通知
@Override
public void onCreate() {
super.onCreate();
service = this;
showNotification();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public void showNotification() {
// PendingIntent如果用户选择此通知,则启动我们的活动
Intent intent = new Intent(MainController.getMainController().getMainActivity(), NotifyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
builder.setSmallIcon(R.mipmap.ic_launcher_m)
.setContentTitle("待唤醒...")//这个显示在通知栏
.setContentIntent(pendingIntent)
.setSound(null)//车震 声音啥的关了
.setVibrate(null)
.setOngoing(true)
.build();
startForeground(NOTIFICATION, builder.build());
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDestroy() {
super.onDestroy();
}
/**
* 清除通知
*/
public void onClearNotify() {
stopForeground(true);
}
}
service 在清单文件注册下 别忘了
<service android:name=".NotificationService" />
然后调用就好了
当我们应用进入后台 并且我们还希望能够监听麦克风
context.startService(new Intent(context, NotificationService.class));
当应用返回前台了,这个通知就多余 我们不想要他
NotificationService.service.onClearNotify();
这样录音的AudioRecord在后台时
int readsize = audioRecord.read(audiodata, 0, audiodata.length);
得到的byte[] audiodata 就不会全是0了