Last active
December 24, 2019 06:52
-
-
Save arunrkwork/efae6a8e7b00577df24f693c192136f7 to your computer and use it in GitHub Desktop.
Android Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.e.handler; | |
import androidx.appcompat.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.os.Handler; | |
import android.os.Message; | |
import android.util.Log; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.ProgressBar; | |
import android.widget.TextView; | |
public class MainActivity extends AppCompatActivity implements View.OnClickListener { | |
private static final String TAG = "MainActivity"; | |
Button btnStar; | |
ProgressBar progressBar; | |
TextView txtCount; | |
int MAX_COUNT = 100; | |
Handler mHandlerThread; | |
private static final int START_PROGRESS = 100; | |
private static final int UPDATE_COUNT = 101; | |
Thread thread; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
btnStar = findViewById(R.id.btnStart); | |
progressBar = findViewById(R.id.progressBar); | |
txtCount = findViewById(R.id.txtCount); | |
progressBar.setMax(MAX_COUNT); | |
btnStar.setOnClickListener(this); | |
thread = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
for (int count = 0; count <= 100; count++) { | |
try { | |
Thread.sleep(100); | |
} catch (InterruptedException ex) { | |
ex.printStackTrace(); | |
} | |
Message message = new Message(); | |
message.what = UPDATE_COUNT; | |
message.arg1 = count; | |
mHandlerThread.sendMessage(message); | |
} | |
} | |
}); | |
} | |
@Override | |
public void onClick(View view) { | |
if (view.getId() == R.id.btnStart) { | |
mHandlerThread.sendEmptyMessage(START_PROGRESS); | |
} | |
} | |
@Override | |
protected void onResume() { | |
super.onResume(); | |
mHandlerThread = new Handler() { | |
@Override | |
public void handleMessage(Message msg) { | |
super.handleMessage(msg); | |
if (msg.what == START_PROGRESS) { | |
thread.start(); | |
} else if (msg.what == UPDATE_COUNT) { | |
txtCount.setText("Progress Count : " + msg.arg1); | |
progressBar.setProgress(msg.arg1); | |
} | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment