Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android write log every seconds in new thread

I want write value from SeekBar to log in new Thread. I want press button and start write logs. and change seekBar value and write it in log.

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, View.OnTouchListener {

    private SeekBar seekBar;
    private Button button;
    private TextView textView;
    private EditText editText;
    private Thread thread;
    private int value = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        button = (Button) findViewById(R.id.button);
        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        seekBar.setOnSeekBarChangeListener(this);
        button.setOnTouchListener(this);
        print();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        value = progress;
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                print();
                Toast.makeText(MainActivity.this, "ACTION_DOWN", Toast.LENGTH_SHORT).show();
                return true; // if you want to handle the touch event
            case MotionEvent.ACTION_UP:
                thread.stop();
                Toast.makeText(MainActivity.this, "ACTION_UP", Toast.LENGTH_SHORT).show();
                return true; // if you want to handle the touch event
        }
        return false;
    }

    public void print() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Log.d("MyLog", String.valueOf(value));
            }
        };
        thread = new Thread(runnable);
        thread.start();
    }
}

but my log write once. How can I write log every second?

like image 272
user5620472 Avatar asked Jun 09 '26 20:06

user5620472


1 Answers

You could do something like this:

Handler handler = new Handler();
boolean stop = false;

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        Log.d("MyLog", String.valueOf(value));

        if (!stop) {
            handler.postDelayed(this, 1000);
        }
    }
};

// start logging by calling this method
public void print() {
    handler.post(runnable);
}

// stop logging by calling this method
public void printStop() {
    stop = true;
}
like image 94
earthw0rmjim Avatar answered Jun 11 '26 11:06

earthw0rmjim