U
U
uvarov-alexvikt2019-11-06 14:20:11
Mobile development
uvarov-alexvikt, 2019-11-06 14:20:11

The application service throws an error when the application closes, what's the problem?

I am writing an android application for taking an exam. Everything works except the service.
I created a service class, it is launched when the form button is clicked and in this service on a timer every 30 seconds. executes the algorithm and displays a message at the top of the screen. If the application is closed or the phone is restarted, the service should work or restart itself and continue to work. I did all this, but with an error, i.e. now, when the service is started by timer, it normally executes the algorithm and displays messages, but when I close the application, a little more time passes than it is set in the timer and a message is displayed: "The application has stopped. Close the application." When the phone is rebooted, the same message is displayed, which means that the service itself starts, but some kind of error stops it. What could be wrong?
Service code:

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");
                }
            }

        }

    }

}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question