How can I show an AlertDialog inside a Progress Bar? - java

I don't know how I can show an AlertDialog, when the progress bar goes
for example to 22%.
I would like when the progress bar reaches 22%, to stop and show an AlertDialog window, showing some text and the default buttons, for example OK and Cancel. When you press OK the progress bar resumes and continues with the progress load. And so complete it until you reach 100% of the progress bar.
The problem is that I don't know how to stop the progress bar, for example at 22% and show the AlertDialog. So this is my doubt. How would be the right way to do it.
This is what I have done so far, and thank you in advance colleagues;)
MainActivity:
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar4;
private int progressStatus4 = 0;
private Handler handler = new Handler();
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
carga();
}
});
}
private void carga(){
final Dialog dialogCorrect = new Dialog(MainActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
final TextView tv44 = dialogCorrect.findViewById(R.id.tv44);
progressBar4 = dialogCorrect.findViewById(R.id.pb44);
final TextView txt = dialogCorrect.findViewById(R.id.txt);
txt.setText("Connect");
if (progressStatus4 == 100) {
progressStatus4 = 0; //Reset Values
}
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus4 < 100) {
progressStatus4 += 1;
try {
Thread.sleep(200);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(progressBar4.getProgress() >= 20 && progressBar4.getProgress() <= 41){
txt.setText("Update");
}else if(progressBar4.getProgress() >= 41 && progressBar4.getProgress() <= 71){
txt.setText("GET");
}else if(progressBar4.getProgress() >= 71 && progressBar4.getProgress() <= 99){
txt.setText("WHAIT");
}else if(progressBar4.getProgress() >= 99 && progressBar4.getProgress() <= 100){
dialogCorrect.dismiss(); //Close PopUp
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(new Runnable() {
#Override
public void run() {
progressBar4.setProgress(progressStatus4);
progressBar4.setSecondaryProgress(progressStatus4 + 15);
// Show the progress on TextView
tv44.setText(progressStatus4 + "%");
}
});
}
}
}).start(); // Start the operation
}
}

Related

how to show a dialog after 1 or 2 min after opning app for first time

I want to show a custom XML dialog dialogue that will appear after a specific time in the first run, let's say after a min
how can I do it
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the app completely
Just as a note - I have already implemented a one time show dialog(directly in main activity without any layout file ) when the app runs for the first time already
Code
To view the already implemented dialog(shows up on the first run) please
go to the // Caution dialog (showDialog method)
MainActivity.java
public class MainActivity extends AppCompatActivity {
MediaPlayer player1;
MediaPlayer player2;
SeekBar seekBar1;
SeekBar seekBar2;
TextView elapsedTimeLable1;
TextView elapsedTimeLable2;
TextView remainingTimeLable1;
TextView remainingTimeLable2;
ImageView play1;
ImageView play2;
int totalTime1;
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String elapsedTime1 = createTimerLable1(currentPosition1);
elapsedTimeLable1.setText(elapsedTime1);
String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
remainingTimeLable1.setText("- " + remainingTime1);
}
};
int totalTime2;
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String elapsedTime2 = createTimerLable2(currentPosition2);
elapsedTimeLable2.setText(elapsedTime2);
String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
remainingTimeLable2.setText("- " + remainingTime2);
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("ObsoleteSdkInt")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
w.setStatusBarColor(ContextCompat.getColor(this, R.color.Card_Elevation_Color));
}
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn1);
play2 = findViewById(R.id.playbtn2);
// TimeLables
elapsedTimeLable1 = findViewById(R.id.cTime1);
elapsedTimeLable2 = findViewById(R.id.cTime2);
remainingTimeLable1 = findViewById(R.id.tTime1);
remainingTimeLable2 = findViewById(R.id.tTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player1.setLooping(true);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player2.setLooping(true);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
if (fromUser1) {
player1.seekTo(progress1);
seekBar1.setProgress(progress1);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
if (fromUser2) {
player2.seekTo(progress2);
seekBar2.setProgress(progress2);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Thread (Update SeekBar & TimeLabel)
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Caution dialog
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
boolean firstStart = preferences.getBoolean("firstStart", true);
if (firstStart) {
showDialog();
}
}
// Caution dialog
private void showDialog() {
new AlertDialog.Builder(this)
.setTitle("Caution!")
.setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
.setPositiveButton("ok", (dialogInterface, i) -> dialogInterface.dismiss())
.create().show();
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
public String createTimerLable1(int duration) {
String timerLabel1 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel1 += min + ":";
if (sec < 10) timerLabel1 += "0";
timerLabel1 += sec;
return timerLabel1;
}
public String createTimerLable2(int duration) {
String timerLabel2 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel2 += min + ":";
if (sec < 10) timerLabel2 += "0";
timerLabel2 += sec;
return timerLabel2;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
#Override
protected void onPause() {
super.onPause();
if (player1 != null) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (player2 != null) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the
app completely
This is impossible to do if your app is closed.My suggestion would be to create a service on another process that does this dialog such that even if the app process is closed,the service process will still be running unless it is stopped explicitly.
Defining a Process of a Service
The android:process field defines the name of the process where the
service is to run. Normally, all components of an application run in
the default process created for the application. However, a component
can override the default with its own process attribute, allowing you
to spread your application across multiple processes.
If the name assigned to this attribute begins with a colon (':'), the
service will run in its own separate process.
<service android:name="com.example.appName" android:process=":externalProcess" />
This is of course in the manifest file .
You might also need to show a system dialog thus you will need a system Alert Window permission i your manifest and request for the permision on runtime.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Then on runtime request like this:
public static void openOverlaySettings(Activity activity) {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName()));
try {
activity.startActivityForResult(intent, 6);
} catch (ActivityNotFoundException e) {
Log.e("Drawers permission :", e.getMessage());
}
}
To check if granted use :
if(!Settings.canDrawOverlays(context)) {
openOverlaySettings(context);
ok=false;
}
Then in your service you should create the dialog like below
View aldv= LayoutInflater.from(act).inflate(R.layout.your_layout,null);
ald=new AlertDialog.Builder(act,R.style.AppTheme)
.setView(aldv)
.setCancelable(true)
.create();
ald.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

How to update TextView dynamically

I'm trying to create a small service that connects to a site does the operations and during the process updates the textview present. Nothing wrong until I enter a for loop, because the activity stops, it becomes completely white until when it does not end.
I would like to update the text step by step.
I created an async task, but it gives me the error '
failed to load window.
Below is my code, I state that I put all the permissions.
public class GameTask extends AsyncTask<String, Integer, Long> {
private ProgressBar progressBar;
private TextView text;
public GameTask(ProgressBar progressBar, TextView text) {
this.progressBar = progressBar;
this.text = text;
}
#Override
protected Long doInBackground(String... strings) {
startGameThread(progressBar, text);
return null;
}
private void startGameThread (final ProgressBar progressBar, final TextView text) {
final Handler mHandler = new Handler();
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
try {
progressBar.setProgress(0);
text.setText("Thread Iniziato...");
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
text.setText("NUMBER " + i);
}
}
progressBar.setProgress(100);
} catch (IOException e) {
e.printStackTrace();
}
}
};
new Thread(mRunnable).start();
}
}
Try this method into AsyncTask
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
try {
progressBar.setProgress(0);
text.setText("Thread Iniziato...");
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
text.setText("NUMBER " + i);
}
}
progressBar.setProgress(100);
} catch (IOException e) {
e.printStackTrace();
}
}
You can take full advantage of AsyncTask to perform tasks in background and UI thread without a Handler:
public class GameTask extends AsyncTask<String, Integer, Long> {
private ProgressBar progressBar;
private TextView text;
public GameTask(ProgressBar progressBar, TextView text) {
this.progressBar = progressBar;
this.text = text;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// UI thread
text.setText("Thread Iniziato...");
}
#Override
protected Long doInBackground(String... strings) {
// Non-UI thread
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
publishProgress(i/100, i);
} else {
publishProgress(i/100);
}
try {
Thread.sleep(100); // Backpressure if needed for your sample
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// UI thread
progressBar.setProgress(values[0]);
if (values.length > 1) {
text.setText("NUMBER " + values[1]);
}
}
}
As this Process is Running Inside AsyncTask, You need to Use runOnUiThread method to update the TextView. UI can only be Upated on MainThread.
private void startGameThread () {
// final Handler mHandler = new Handler();
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
final int finalI = i;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(String.valueOf(finalI));
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(mRunnable).start();
}

Monitoring Voice in my android app

Iam making an android app which monitor voice in which when the voice loudness exceed a user defined threshold the app dial a specific number .
i done making voice monitoring and compared the highest value with the threshold then dialling the number .everything goes right except when the app returned after the call i find the monitoring isnt right , as the mic sensitivity is very week (measurement is very low ) i have to restart the app to obtain the right measurement , the second question here i make the comparison of the threshold and the last value of sound in the handler at the bottom , is this the right way ? thanks in advanceThis is the App image
Below is The Main activity
public class MainActivity extends AppCompatActivity {
private static final int sampleRate = 11025;
private static final int bufferSizeFactor = 10;
private Button Stop;
private ProgressBar On;
private Button Start;
private AudioRecord audio;
private int bufferSize;
private ProgressBar level;
private TextView textView;
volatile int threshold;
TextView testtextview;
private boolean clicked ;
private Handler handler = new Handler();
private int lastLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threshold = 20000;
//progressbar detect voice
level = (ProgressBar) findViewById(R.id.progressbar_level);
level.setMax(32676);
//text displaying progress par value
textView = (TextView) findViewById(R.id.textView1);
testtextview = (TextView) findViewById(R.id.textViewtest);
if (audio != null) {
audio.stop();
audio.release();
audio = null;
handler.removeCallbacks(update);
} else {
bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT) * bufferSizeFactor;
audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audio.startRecording();
Thread thread = new Thread(new Runnable() {
public void run() {
readAudioBuffer();
}
});
thread.setPriority(Thread.currentThread().getThreadGroup().getMaxPriority());
thread.start();
handler.removeCallbacks(update);
handler.postDelayed(update, 25);
}
//seekbar let user choose threshhold
SeekBar mSeekBar = (SeekBar) findViewById(R.id.seekBar);
//text displayin user choice
final TextView textViewuser = (TextView) findViewById(R.id.textView3);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textViewuser.setText("" + i + "/32676");
threshold = i ;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Stop = (Button) findViewById(R.id.dummy_buttonstop);
On = (ProgressBar) findViewById(R.id.progressBar11);
Start = (Button) findViewById(R.id.dummy_button);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Start.setVisibility(View.GONE);
On.setVisibility(View.VISIBLE);
clicked = true;
}
});
Stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
clicked = false;
}
});
}
private void readAudioBuffer() {
try {
short[] buffer = new short[bufferSize];
int bufferReadResult;
do {
bufferReadResult = audio.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++) {
if (buffer[i] > lastLevel) {
lastLevel = buffer[i];
}
}
}
while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);
if (audio != null) {
audio.release();
audio = null;
handler.removeCallbacks(update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Runnable update = new Runnable() {
public void run() {
MainActivity.this.level.setProgress(lastLevel);
textView.setText(lastLevel + "/" + level.getMax());
if (clicked) {
if (lastLevel > threshold) {
clicked=false;
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
String url = "tel:01224271138";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//recreate();
}
}
lastLevel *= .5;
handler.postAtTime(this, SystemClock.uptimeMillis() + 500);
}
};

How to frequently update number in EditText from loop?

My Code should frequently update a number (not only show the result, delay of 100) from a loop in an EditText after you click on a button.
Old Code:
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
while (repeat > 0) {
num1 = new Random().nextInt(6)+1;
edit1.setText(String.valueOf(num1));
repeat = repeat - 1;
rep.setText(String.valueOf(repeat));
}
}
});
Now I have this:
final Handler randomHandler = new Handler();
final Runnable randomUpdate = new Runnable() {
#Override
public void run() {
num1 = new Random().nextInt(6) + 1;
edit1.setText(String.valueOf(num1));
repeat--;
rep.setText(String.valueOf(repeat));
randomHandler.postDelayed(this, 1000);
}
};
btnpl5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
repeat = repeat + 5;
rep.setText(String.valueOf(repeat));
button2.setClickable(true);
button2.setEnabled(true);
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
randomUpdate.run();
button2.setClickable(false);
button2.setEnabled(false);
}
Problem: it won't stop after repeat is 0 (it goes on -1 -2 -3 -4 ..)?
You must always be on the UI thread when calling any method on any
view. If you are doing work on other threads and want to update the
state of a view from that thread, you should use a Handler.
Try this,
handler.postDelayed(new Runnable(){
#Override
public void run() {
num1 = new Random().nextInt(6)+1;
// get previous value and append new generated
edit1.setText(edit1.getText().toString()+String.valueOf(num1));
}
}, (1000)); // run this method in every 1000 milliseconds
This may help you.
You can use an AsyncTask to delay in the background, and publishProgress() to update the UI.
class TextDisplayTask extends AsyncTask<Integer, Integer, Void> {
private int DELAY_MILLIS = 100; // ... set your delay here
#Override
protected Void doInBackground(Integer... params) {
for (int i = 0; i < params[0]; i++) {
int num = new Random().nextInt(6) + 1;
publishProgress(num);
Thread.sleep(DELAY_MILLIS);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
edit1.setText(String.valueOf(values[0]));
}
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new TextDisplayTask().execute(20); // show a number 20 times
}
});

Progress bar only load one time

My progress bar can only use one time,when i click it second time,it likes a loop,never end,what is the problem?
class ProgressThread extends Thread {
final static int DONE = 0;
final static int RUNNING = 1;
int maxBarValue=100;
int delay=40;
Handler mHandler;
int mState;
int total;
// Constructor with an argument that specifies Handler on main thread
// to which messages will be sent by this thread.
ProgressThread(Handler h) {
mHandler = h;
}
#Override
public void run() {
mState = RUNNING;
total = maxBarValue;
while (mState == RUNNING) {
// The method Thread.sleep throws an InterruptedException if Thread.interrupt()
// were to be issued while thread is sleeping; the exception must be caught.
try {
// Control speed of update (but precision of delay not guaranteed)
Thread.sleep(delay);
} catch (InterruptedException e) {
Log.e("ERROR", "Thread was Interrupted");
}
// Send message (with current value of total as data) to Handler on UI thread
// so that it can update the progress bar.
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total--; // Count down
}
total=maxBarValue;
}
public class ProgressBarActivity extends Activity {
ProgressThread progThread;
ProgressDialog progDialog;
Button button1, button2;
int typeBar; // Determines type progress bar: 0 = spinner, 1 = horizontal
int delay = 40; // Milliseconds of delay in the update loop
int maxBarValue = 200; // Maximum value of horizontal progress bar
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Process button to start spinner progress dialog with anonymous inner class
button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
typeBar = 0;
showDialog(typeBar);
}
});
// Process button to start horizontal progress bar dialog with anonymous inner class
button2 = (Button) findViewById(R.id.Button02);
button2.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
typeBar = 1;
showDialog(typeBar);
}
});
}
// Method to create a progress bar dialog of either spinner or horizontal type
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case 0: // Spinner
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDialog.setMessage("Loading...");
progThread = new ProgressThread(handler);
progThread.start();
return progDialog;
case 1: // Horizontal
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progDialog.setMax(maxBarValue);
progDialog.setMessage("Dollars in checking account:");
progThread = new ProgressThread(handler);
progThread.start();
return progDialog;
default:
return null;
}
}
// Handler on the main (UI) thread that will receive messages from the
// second thread and update the progress.
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// Get the current value of the variable total from the message data
// and update the progress bar.
int total = msg.getData().getInt("total");
progDialog.setProgress(total);
if (total <= 0){
dismissDialog(typeBar);
progThread.setState(ProgressThread.DONE);
}
}
};
}
// Set current state of thread (use state=ProgressThread.DONE to stop thread)
public void setState(int state) {
state=ProgressThread.DONE;
mState = state;
}
}
ProgressBar.postInvalidate() you can try this.

Categories