Сервис приложения выдает ошибку когда закрывается приложение, в чем мб проблема?

Ответить
uvarov-alexvikt
Сообщения: 4
Зарегистрирован: 04 июл 2019, 12:37

Сервис приложения выдает ошибку когда закрывается приложение, в чем мб проблема?

Сообщение uvarov-alexvikt » 06 ноя 2019, 14:23

Пишу приложение на Android для сдачи экзамена. Все работает кроме сервиса.
Я создал класс service, он запускается при нажатии на кнопку формы и в этом сервисе по таймеру каждые 30 сек. отрабатывает алгоритм и выводит сообщение в верху экрана. Если приложение закрыть или перезагрузить телефон, сервис должен работать или сам перезапускаться и продолжать работать. Все это я сделал, но с ошибкой, т.е. сейчас при запуске сервиса по таймеру он штатно отрабатывает алгоритм и выводит сообщения, но когда я закрываю приложение, проходит чуть больше времени чем заложено в таймере и выдается сообщение: "Приложение остановлено. Закрыть приложение". При перезагрузке телефона выдается такое же сообщение, значит сервис сам стартует, но какая то ошибка его прекращает. В чем может быть ошибка?
Код сервиса:

Код: Выделить всё

public class AvtoProvShtServ extends Service {
    private NotificationManager notificationManager;
    public static final int DEFAULT_NOTIFICATION_ID = 101;
    private static final String SHTAFIPDD_MY_SETTINGS = "shtrafiPDD_MY_SETTINGS";
    private Timer mTimer;
    private TimerTask mTimerTask;
    private String strDate = "";
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
    }

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

        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        //Task
        mTimer.schedule(mTimerTask, 1000, 30000);
       return START_REDELIVER_INTENT;
    }

    public void sendNotification(String Ticker,String Title,String Text) {

       Intent notificationIntent = new Intent(this, MainActivity_OkHTTP_ProvSht.class);
       notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager notificationManager =(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
        NotificationCompat.Builder builder = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
            notificationManager.createNotificationChannel(notificationChannel);
            builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
        } else {
            builder = new NotificationCompat.Builder(getApplicationContext());
        }

        builder = builder
                .setContentIntent(contentIntent)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Внимание, найден штраф!")
                .setTicker("Внимание, штраф!")
                .setContentText("Посмотреть найденные штрафы")
                .setDefaults(Notification.DEFAULT_ALL)
                .setAutoCancel(true);
        notificationManager.notify(DEFAULT_NOTIFICATION_ID, builder.build());

    }


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


    @Override
    public void onDestroy() {
        super.onDestroy();
        notificationManager.cancel(DEFAULT_NOTIFICATION_ID);
        stopSelf();
    }

    private String formattedDate;
    private String formattedDateSohr;
    private String peremsluch;
    private SimpleDateFormat df;
    private Calendar calendar;
    private Date date1;
    private Random randommin;
    private Random randomHo;
    private Random randomsec;
    private int chas;
    private long sohdatInt;
    private long tekdatInt;

    private String bodyR ="";
    private String datPostanov ="";
    private String shtStrAr = "";
    private String shtStrName = "";
    private String kolshSt ="";
    private String rezkon ="";
    private String[][] masIdSht;
    private String oplOrnoopl3 = "";
    private String svidRegTS;
    private String gosNomTS;
    private String novEmail = "";
    private String iDTSSoh = "";
    class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            SharedPreferences settings = getSharedPreferences(SHTAFIPDD_MY_SETTINGS, Context.MODE_PRIVATE);
            formattedDateSohr =settings.getString("PoslZapServ", "");
            sohdatInt = Long.parseLong(formattedDateSohr);

                calendar = Calendar.getInstance();
                df = new SimpleDateFormat("yyyyMMddhhmmss", Locale.getDefault());
                formattedDate = df.format(calendar.getTime());
                tekdatInt = Long.parseLong(formattedDate);

            formattedDate = df.format(calendar.getTime());

            randomHo = new Random();
            peremsluch = String.valueOf(randomHo.nextInt(4));
            chas = Integer.parseInt(peremsluch);
            calendar.add(Calendar.HOUR,72+chas);
            formattedDate = df.format(calendar.getTime());

            randommin = new Random();
            peremsluch = String.valueOf(randommin.nextInt(59));
            chas = Integer.parseInt(peremsluch);
            calendar.add(Calendar.MINUTE,chas);
            formattedDate = df.format(calendar.getTime());

           randomsec  = new Random();
            peremsluch = String.valueOf(randomsec.nextInt(59));
            chas = Integer.parseInt(peremsluch);
            calendar.add(Calendar.SECOND,chas);
            formattedDate = df.format(calendar.getTime());

            SharedPreferences.Editor editor = settings.edit();
            editor.putString("PoslZapServ", formattedDate );
            editor.apply();

            iDTSSoh = settings.getString("IDTS_1", "");
            if(iDTSSoh!="") {


                OkHttpClient clientShtrPolTS = new OkHttpClient();

                String ZapStr = iDTSSoh;
                oplOrnoopl3 ="paid";//nopaid
                Request requestclientShtrPolTS = new Request.Builder()
                        .addHeader("Authorization","Bearer kode1")
                        .url("https://api.test1.ru/cars/"+ZapStr+"/fines?paid="+oplOrnoopl3+"&doc=all&org=all")
                        .get()
                        .build();

                try {Response responseShtrPolTS = clientShtrPolTS.newCall(requestclientShtrPolTS).execute();
                    if (responseShtrPolTS.code()==200);//(!responseShtrPolTS.isSuccessful()) throw new IOException("Unexpected code " + responseShtrPolTS);
                    bodyR = responseShtrPolTS.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    JSONObject jsonShtKon = new JSONObject(bodyR);
                    kolshSt = jsonShtKon.getString("count");
                    String oplOrnoopl = "";
                } catch (JSONException e3) {
                    e3.printStackTrace();

                }
                Byte kolShInt = Byte.parseByte(kolshSt);
                if (kolShInt > 0) {
                    editor.putString("shtNaydServ", "true" );
                    editor.putString("shtNaydBodyR", bodyR );
                    editor.apply();
                    sendNotification("Ticker","Title","Text");
                }
            }

        }

    }

}

Ответить