Переключатель панели быстрой настройки Android иногда сбрасывается в выключенное положение, когда я держал его в фоновом режиме

Итак, я работаю над трекером для отслеживания привычек Activity, который является частью основного приложения StudyProgress от Niral.

TileService.java показан следующим образом

package com.niralnaik.studyprogress;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Icon;
import android.icu.text.SimpleDateFormat;
import android.preference.PreferenceManager;
import android.service.quicksettings.Tile;
import android.widget.Toast;

import java.util.Date;
import java.util.Locale;

public class TileService extends android.service.quicksettings.TileService {
    String timeOfStudy,timeOfRest,LogSTART,LogEND;
    public static final String START_TIME="startTime";
    public static final String END_TIME="endTime";
    public static final String HABIT="habit";
    private final int STATE_ON=1;
    private final int STATE_OFF=0;
    private int toggle= STATE_ON;
    @Override
    public void onTileAdded() {
        super.onTileAdded();
    }

    @Override
    public void onStartListening() {
        Tile tile =getQsTile();
    }

    @Override
    public void onClick() {
        Icon icon;

        if(toggle==STATE_ON){
            toggle=STATE_OFF;
            timeOfStudy=new SimpleDateFormat("h:m:s a", Locale.getDefault()).format(new Date());
            LogSTART="Started "+new SimpleDateFormat("EEE, d MMM yyyy h:m a", Locale.getDefault()).format(new Date())+" \n";
            icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_menu_book_24);
            Toast.makeText(getApplicationContext(),LogSTART,Toast.LENGTH_SHORT).show();
            SharedPreferences sharedPreferences = PreferenceManager
                    .getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            String value = sharedPreferences.getString(HABIT,"");
            String appendedValue =value+LogSTART;
            editor.putString(HABIT,appendedValue);
            editor.putString(START_TIME,timeOfStudy);
            editor.apply();
        }else {
            if(toggle==STATE_OFF){
                toggle=STATE_ON;
                icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_sports_football_24);
                LogEND="Ended "+new SimpleDateFormat("EEE, d MMM yyyy h:m a", Locale.getDefault()).format(new Date())+" \n";
                timeOfRest=new SimpleDateFormat("h:m:s a", Locale.getDefault()).format(new Date());
                Toast.makeText(getApplicationContext(),LogEND,Toast.LENGTH_SHORT).show();
                SharedPreferences sharedPreferences = PreferenceManager
                        .getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                String value = sharedPreferences.getString(HABIT,"");
                String appendedValue =value+LogEND;
                editor.putString(HABIT,appendedValue);
                editor.putString(END_TIME,timeOfRest);
                editor.apply();
            }else {
                icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_launcher2_foreground);
                Toast.makeText(getApplicationContext(),"Press again",Toast.LENGTH_SHORT).show();
            }


        }
        getQsTile().setIcon(icon);
        getQsTile().updateTile();
    }

}

и он действительно работает отлично, но иногда он выполняет TOGGLE STATE ON Вместо этого он должен вести себя для TOGGLE STATE OFF... Я думаю, он забывает предыдущее действие, которое я уже сделал TOGGLE STATE OFF, и время для выполнения части TOGGLE STATE OFF....

РЕДАКТИРОВАТЬ:

    public static final String TOGGLE_POSITION="position";

реализован sharedpref для сохранения позиции

 @Override
    public void onClick() {
        Icon icon;
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        toggle=sharedPreferences.getInt(TOGGLE_POSITION,STATE_ON);

        if(toggle==STATE_ON){
            toggle=STATE_OFF;
            timeOfStudy=new SimpleDateFormat("h:m:s a", Locale.getDefault()).format(new Date());
            LogSTART="Started "+new SimpleDateFormat("EEE, d MMM yyyy h:m a", Locale.getDefault()).format(new Date())+" \n";
            icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_menu_book_24);
            Toast.makeText(getApplicationContext(),LogSTART,Toast.LENGTH_SHORT).show();
            SharedPreferences.Editor editor = sharedPreferences.edit();
            String value = sharedPreferences.getString(HABIT,"");
            String appendedValue =value+LogSTART;
            editor.putInt(TOGGLE_POSITION,toggle);
            editor.putString(HABIT,appendedValue);
            editor.putString(START_TIME,timeOfStudy);
            editor.apply();
        }else {
            if(toggle==STATE_OFF){
                toggle=STATE_ON;
                icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_sports_football_24);
                LogEND="Ended "+new SimpleDateFormat("EEE, d MMM yyyy h:m a", Locale.getDefault()).format(new Date())+" \n";
                timeOfRest=new SimpleDateFormat("h:m:s a", Locale.getDefault()).format(new Date());
                Toast.makeText(getApplicationContext(),LogEND,Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = sharedPreferences.edit();
                String value = sharedPreferences.getString(HABIT,"");
                editor.putInt(TOGGLE_POSITION,toggle);
                String appendedValue =value+LogEND;
                editor.putString(HABIT,appendedValue);
                editor.putString(END_TIME,timeOfRest);
                editor.apply();
            }  else {
                icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_launcher2_foreground);
                Toast.makeText(getApplicationContext(),"Press again",Toast.LENGTH_SHORT).show();
            }
        }
        getQsTile().setIcon(icon);
        getQsTile().updateTile();
    }

Думаю, теперь это может сработать..

    @Override
    public void onStartListening() {
        Tile tile =getQsTile();
        Icon icon = null;
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        toggle=sharedPreferences.getInt(TOGGLE_POSITION,STATE_ON);
        if(toggle == STATE_ON){
            icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_menu_book_24);
        }
        if(toggle==STATE_OFF){
            icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_sports_football_24);
        }
        getQsTile().setIcon(icon);
        getQsTile().updateTile();
    }

добавил это, так как он не запоминает позицию при ПЕРЕЗАГРУЗКЕ

НИЖЕ КОД РЕШЕННОЙ КОНЕЧНОЙ ПРОБЛЕМЫ.

public class TileService extends android.service.quicksettings.TileService {
    String timeOfStudy,timeOfRest,LogSTART,LogEND;
    public static final String START_TIME="startTime";
    public static final String END_TIME="endTime";
    public static final String HABIT="habit";
    public static final String TOGGLE_POSITION="position";
    private final int STATE_ON=1;
    private final int STATE_OFF=0;
    private int toggle;
    Icon icon;
    @Override
    public void onTileAdded() {
        super.onTileAdded();
    }

    @Override
    public void onStartListening() {
        Tile tile =getQsTile();
        setToggle();
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        toggle=sharedPreferences.getInt(TOGGLE_POSITION,STATE_ON);

    }

    private void setToggle() {
        if(toggle == STATE_ON){
            icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_menu_book_24);
        }
        if(toggle==STATE_OFF){
            icon=Icon.createWithResource(getApplicationContext(),R.drawable.ic_baseline_sports_football_24);
        }
        getQsTile().setIcon(icon);
        getQsTile().updateTile();
    }


    @Override
    public void onClick() {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        toggle=sharedPreferences.getInt(TOGGLE_POSITION,STATE_ON);
        if(toggle==STATE_ON){
            toggle=STATE_OFF;
            setToggle();
            timeOfStudy=new SimpleDateFormat("h:m:s a", Locale.getDefault()).format(new Date());
            LogSTART="Started "+new SimpleDateFormat("EEE, d MMM yyyy h:m a", Locale.getDefault()).format(new Date())+"\n";
            Toast.makeText(getApplicationContext(),LogSTART,Toast.LENGTH_SHORT).show();
            SharedPreferences.Editor editor = sharedPreferences.edit();
            String value = sharedPreferences.getString(HABIT,"");
            String appendedValue =value+LogSTART;
            editor.putInt(TOGGLE_POSITION,toggle);
            editor.putString(HABIT,appendedValue);
            editor.putString(START_TIME,timeOfStudy);
            editor.apply();
        }else {
            if(toggle==STATE_OFF){
                toggle=STATE_ON;
                setToggle();
                LogEND="Ended "+new SimpleDateFormat("EEE, d MMM yyyy h:m a", Locale.getDefault()).format(new Date())+"\n";
                timeOfRest=new SimpleDateFormat("h:m:s a", Locale.getDefault()).format(new Date());
                Toast.makeText(getApplicationContext(),LogEND,Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = sharedPreferences.edit();
                String value = sharedPreferences.getString(HABIT,"");
                editor.putInt(TOGGLE_POSITION,toggle);
                String appendedValue =value+LogEND;
                editor.putString(HABIT,appendedValue);
                editor.putString(END_TIME,timeOfRest);
                editor.apply();
            }
        }
        getQsTile().updateTile();
    }

}

0 ответов

Другие вопросы по тегам