接收器无法启动服务

nxowjjhe  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(164)

在我的应用程序中启动了一个服务,它倒计时,然后向接收器发送一个信号,接收器必须启用另一个服务来播放音乐和振动设备。如果设备未处于睡眠模式,则播放服务启动;如果处于睡眠模式,则播放服务也启动;如果时间在睡眠模式下长达5分钟;如果超过5分钟,则播放旋律的服务不启动。接收器代码:

receiverStartQuestion=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //останавливаем сервис
            //Intent serviceIntent = new Intent(context, ServiceWork.class);System.out.println("BROAD");
            //context.stopService(serviceIntent);
            //stopService(new Intent(MainActivity.this, ServiceWork.class));
            //создаем и выводим в трей уведомление
            constants.notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            String channelId = "my_channel_id";
            CharSequence channelName = "My Channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel notificationChannel = null;
            Intent notificationIntent = new Intent(MainActivity.this, activity_question.class);
            PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this,
                    0, notificationIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notificationChannel = new NotificationChannel(channelId, channelName, importance);
                notificationChannel.enableLights(true);
                notificationChannel.setLightColor(Color.RED);
                notificationChannel.enableVibration(true);
                notificationChannel.setVibrationPattern(new long[]{1000, 2000});
                constants.notificationManager.createNotificationChannel(notificationChannel);
            }
            Notification notification=null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notification = new Notification.Builder(getApplicationContext(), channelId)
                        .setContentTitle(getString(R.string.text17))
                        .setContentText(getString(R.string.text51))
                        .setSmallIcon(R.drawable.question)
                        .setContentIntent(contentIntent)
                        .setDeleteIntent(contentIntent)
                        .build();
            }else{
                notification = new Notification.Builder(getApplicationContext())
                        .setContentTitle(getString(R.string.text17))
                        .setContentText(getString(R.string.text51))
                        .setSmallIcon(R.drawable.question)
                        .setContentIntent(contentIntent)
                        .setDeleteIntent(contentIntent)
                        .build();
            }
            constants.notificationManager.notify(100, notification);
            if(constants.alarm==true || constants.vibro==true){
                Intent Intent = new Intent(MainActivity.this, ServiceAudio.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(Intent);
                }else startService(new Intent(MainActivity.this, ServiceAudio.class));
            }
        }
    };

演奏旋律的服务等级:

public class ServiceAudio extends Service {
MediaPlayer mPlayer;
Vibrator vibrator;
private static final int ID_SERVICE = 101;
public ServiceAudio() {
}
//при запуске сервиса
public int onStartCommand(Intent intent, int flags, int startId) {
    //проигрывание музыки
    if(constants.alarm) {
        if (constants.number_melody == 0) mPlayer = MediaPlayer.create(this, R.raw.melody);
        else {
            String wayMelody = Environment.way + "Music/melody.mp3";
            File file = new File(Environment.way + "Music/", "melody.mp3");
            if (file.exists()) {
                try {
                    mPlayer = new MediaPlayer();
                    mPlayer.setDataSource(Environment.way + "Music/melody.mp3");
                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else mPlayer = MediaPlayer.create(this, R.raw.melody);
        }
        mPlayer.setLooping(true);
        mPlayer.start();
    }
    //вибрация
    if(constants.vibro){
        long[] pattern = { 500, 1000 };
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(pattern, 0);
    }
    return START_STICKY;
}
//при удалении сервиса
@Override
public void onDestroy() {
    super.onDestroy();
    if (constants.alarm)mPlayer.stop();
    if (constants.vibro)vibrator.cancel();
}
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
    super.onCreate();
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build();
    startForeground(ID_SERVICE, notification);
}

@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
    String channelId = "my_service_channelid";
    String channelName = "My Foreground Service";
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    // omitted the LED color
    channel.setImportance(NotificationManager.IMPORTANCE_NONE);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return channelId;
}

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题