Команды вибрации и уведомления не работают

1

Я работаю над приложением для пожарной сигнализации. По сути, я пытаюсь создать фоновый сервис, который будет уведомлять пользователя и вибрировать устройство, когда конкретный веб-сайт запущен. Этот веб-сайт создан Node mcu, который запускается датчиком дыма или пламени. Я новичок в Android Studio, но после некоторых исследований я написал следующий код, но он не работает. Попытался отладить его, но не смог кто-нибудь сказать мне, что идет не так???

Вот код, который я написал для сервиса -

 public class ExampleService extends Service {
    int flag=0;
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        final Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Fire Alarm Service")
                .setContentText("Alarm system is functional")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .build();


        Timer repeatTask = new Timer();
        repeatTask.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                if (isInternetAvailable()){
                    flag = 1;
                }else{
                    flag = 0;
                }
                System.out.println("pingHost flag: " + flag );
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (flag == 1) {
                            startForeground(1, notification);
                            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                v.vibrate(VibrationEffect.createOneShot(5000, VibrationEffect.DEFAULT_AMPLITUDE));
                            } else {
                                //deprecated in API 26
                                v.vibrate(5000);
                            }
                        }
                    }
                });
            }
        }, 0, 10000);


        return START_NOT_STICKY;
    }
 public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com");
            //You can replace it with your name
            return !ipAddr.equals("");

        }
        catch (Exception e) {
            return false;
        }
    }
}

Обе команды Vibration и Notification работают вне Timertask, поэтому я попытался запустить код вне задачи таймера, но, похоже, он не работает. Также этот флаг и доступная в Интернете логика работает должным образом.... Заранее спасибо!

Теги:
android-studio
timertask

1 ответ

0

ОБНОВЛЕНИЕ: я сделал некоторые изменения после отладки, и теперь код работает. Не знаю, почему раньше это не было, но все еще хорошо сейчас. Спасибо!

Код после изменения:

public class ExampleService extends Service {
    int flag2=0;
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Timer repeatTask = new Timer();
        repeatTask.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                if (isInternetAvailable()){
                    flag2 = 1;
                }else{
                    flag2 = 0;
                }
                System.out.println("pingHost flag2: " + flag2 );
                if (flag2 == 1) {
                    notif();
                }
            }
    }, 0, 10000);

        return START_STICKY; }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com");
            //You can replace it with your name
            return !ipAddr.equals("");

        }
        catch (Exception e) {
            return false;
        }
    }

    public void notif() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Fire Alarm Service")
                .setContentText("Fire Detected in D building")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);

        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(5000, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            //deprecated in API 26
            v.vibrate(5000);
        }
    }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню