This code is from a book. a Progress Dialog seems to be shown in non-UI thread.
But as I know only in the UI thread It is possible.
I wonder why it is possible to show a ProgressDialog in non-Ui thread.
public class BackWork3 extends Activity
{
TextView mResult;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.backwork);
mResult = (TextView)findViewById(R.id.result);
}
public void mOnClick(View v)
{
int start = 0, end = 100;
int result;
WaitDlg dlg = new WaitDlg(BackWork3.this, "WaitTest", "Now calculating");
dlg.start();
result = Accumulate(start, end);
mResult.setText("" + result);
WaitDlg.stop(dlg);
}
int Accumulate(int start, int end)
{
int sum = 0;
for (int i = start; i <= end; i++)
{
sum += i;
try { Thread.sleep(20); } catch (InterruptedException e) {;}
}
return sum;
}
}
class WaitDlg extends Thread
{
Context mContext;
String mTitle;
String mMsg;
ProgressDialog mProgress;
Looper mLoop;
WaitDlg(Context context, String title, String msg)
{
mContext = context;
mTitle = title;
mMsg = msg;
setDaemon(true);
}
public void run()
{
Looper.prepare();
mProgress = new ProgressDialog(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setTitle(mTitle);
mProgress.setMessage(mMsg);
mProgress.setCancelable(false);
mProgress.show();
mLoop = Looper.myLooper();
Looper.loop();
}
static void stop(WaitDlg dlg)
{
dlg.mProgress.dismiss();
try { Thread.sleep(100); } catch (InterruptedException e) {;}
dlg.mLoop.quit();
}
}
//------------------------------------------------------------------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="mOnClick"
android:text="Start"
/>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40sp"
android:text="result"
/>
</LinearLayout>
The code is using Looper inside non UI thread that creates a handler and this looper becomes a reference to that Handler. This way you can play with UI elements in non UI thread.
According to Docs.
Looper.Prepare():
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop.
Hope this helps
Related
**I configured a simple single TextView layout (see below after the code) to change the display changing from 10 up to 20. What I see is "20" being displayed. My code is as follows. Want to know why only the last number ("20") is displayed omitting the intermediate ones(10 thru 19))
package com.example.test;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class TestActivity extends Activity {
public TextView mytv;
public Toast mtoast;
#Override
protected void onCreate(Bundle savedInstanceState) {
int i = 10;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mytv = (TextView) findViewById(R.id.myhw);
mtoast = Toast.makeText(this, String.valueOf(i), Toast.LENGTH_LONG);
while (i++ < 20) {
mtoast.setText(String.valueOf(i));
mtoast.show();
mytv.setText(String.valueOf(i));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
The relevant layout is as follows.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".TestActivity" >
<TextView
android:id="#+id/myhw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
because the view is not shown until onResume call and after that the activity is displayed, all you are doing is changing the view content in onCreate method, after onCreate activity goes to onStart and onResume so when onCreate finishes the textView value is 20 and after onResume it sets the value to 20.
for more information look at activity life cycle at :
http://developer.android.com/reference/android/app/Activity.html
You shouldn't sleep the UI thread in the first place.
What you probably want to do is to use another thread, let it sleeps for a couple of seconds and, each time you update the UI, use the UI (main) thread. You can do it in several ways, but the simples probably is using an AsyncTask, as:
public class MyActivity extends Activity {
public TextView mytv;
public Toast mtoast;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
i = 10;
mytv = (TextView) findViewById(R.id.myhw);
mtoast = Toast.makeText(this, String.valueOf(i), Toast.LENGTH_LONG);
new AsyncTask<Void, String, Void>() {
#Override
protected Void doInBackground(Void... voids) {
while (i < 20) {
publishProgress(String.valueOf(i));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
mtoast.setText(values[0]);
mtoast.show();
mytv.setText(values[0]);
}
}.execute();
}
}
Want to know why only the last number ("20") is displayed omitting the intermediate ones(10 thru 19))
It doesn't work because you sleep the UI Thread.
To make this work, you would have to do it through a Thread, you can use an AsyncTask for this, or a Timer object as i specified below, anyways i recommend the use of AsyncTask.
Once i was doing something simmilar, you could use a Timer object for this.
Using the method: scheduleAtFixedRate(TimerTask task, long delay, long period)
The Docs for this method says
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
It means after the seconds from the second parameter, it will start, using the third parameter as delay for each execution. You will have to cancel it, calling the method:cancel();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (counter == 20) {
timer.cancel();
counter = 0;
time.setText("Ta-da! I'm Done ");
}else{
counter += 1;
if (time != null)
time.setText(String.valueOf(counter));
}
}
});
}
}, delay, period);
Even further: A Thread.sleep is not the proper way to update a GUI and watch how it changes. The value it will take is the last one. The activity will be blocked until the last is shown.
If you want to see that effect, you should programm a Thread which communicates the main thread every X seconds, and the main thread should listen the Thread to change it.
For example, you could use an AsyncTask and use onProgressUpdate.
Edited with some code:
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume(){
super.onResume();
/* Running AsyncTask */
myAsyncTask bkg = new myAsyncTask();
/* I'll pass an integer parameter: milliseconds to wait. */
bkg.execute(3000);
}
private class myAsyncTask extends AsyncTask<Integer, Integer, String> {
#Override
protected void onPreExecute() {
/* TODO: Do BEFORE background process */
Toast.makeText(getApplicationContext(),"I'm going to do a background task!", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Integer... parameters) {
/* TODO: What to do in Background */
/* Retrieving parameter passed */
int milliseconds = parameters[0];
try {
Thread.sleep(milliseconds);
publishProgress(milliseconds); /* Will prompt that value */
} catch (InterruptedException e) {
e.printStackTrace();
return "ERROR";
}
int i = 0;
while (i++ < 20) {
try {
Thread.sleep(milliseconds);
publishProgress(i);
} catch (InterruptedException e) {
e.printStackTrace();
return "ERROR";
}
}
return "OK";
}
#Override
protected void onPostExecute(String result) {
/* TODO: After execution of thread */
if(result.equals("OK"))
Toast.makeText(getApplicationContext(),"Correctly Processed", Toast.LENGTH_SHORT).show();
if(result.equals("ERROR"))
Toast.makeText(getApplicationContext(),"Failed", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... values) {
/* TODO: Here you can access UI elements as your TextView */
TextView tv = (TextView) findViewById(R.id.tvExample);
tv.setText(values[0]+"");
}
}
}
layout/main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.myapplication2.app.MainActivity"
android:id="#+id/whatever">
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/tvExample" />
Use the code (tested on device) provided below:
public class TestActivity extends Activity {
private Handler mHandler;
public TextView mytv;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toast_showing_acounter);
mytv = (TextView) findViewById(R.id.myhw);
mHandler = new Handler();
i = 10;
scheduleHandler();
}
private void scheduleHandler() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
showCounter();
if (i < 20) {
scheduleHandler();
}
}
}, 5000);
}
private void showCounter() {
Toast.makeText(this, String.valueOf(i), Toast.LENGTH_LONG).show();
mytv.setText(String.valueOf(i));
i++;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
i want to increment a progress dialog from a thread inside a service, i have really hard time doing that, this is my code please help me.
I tried many different ways including asyncTask (I had problem with context)
and tried with static functions but its not working properly,
I pretty new with android please explain me the problem here.
the activity
public class MainActivity extends Activity {
ProgressDialog progressBar;
private void showProgrssBar() {
progressBar.show();
}
private void dismissProgressBar() {
progressBar.dismiss();
}
private void increaseProgressBar(int total) {
progressBar.incrementProgressBy(total);
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createProgressBarDialog();
Intent n = new Intent(this, myService.class);
startService(n);
}
private void createProgressBarDialog()
{
progressBar = new ProgressDialog(this);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setMax(200);
progressBar.setMessage("Recieving bluetooth data");
progressBar.setCanceledOnTouchOutside(false);
}
the service:
public class myService extends Service
{
private myThread myThread;
Handler handler = new Handler()
{
#Override
public void handleMessage(android.os.Message msg)
{
int total = msg.getData().getInt("total");
if (total == -1)
{
dismissProgressBar();
}
else if (total == 0)
{
showProgrssBar();
}
else
{
increaseProgressBar(total);
}
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
myThread = new myThread(handler);
myThread.start();
return START_STICKY;
}
the thread
class myThread extends Thread
{
Handler h;
int numOfLinesToRead = 220;
int line = 0;
public myThread(Handler h)
{
this.h = h;
}
private void increaseProgressBarOnActivity(int i_MsgType)
{
Message msg = h.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", i_MsgType);
msg.setData(b);
h.sendMessage(msg);
}
#Override
public void run() {
super.run();
int increase;
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
for (; line < 220; line++)
{
increase = (line*100/numOfLinesToRead);
if (increase != 0)
{
increaseProgressBarOnActivity(increase);
try
{
Thread.sleep(90);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
Despite you having already tried AsyncTask, I still would strongly recommend to use it.
Just take a look at the onProgressUpdate() method. It is made to update the UI from AsyncTask.
Here is an example of how it could look like:
private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
private ProgressDialog progressBar;
#Override
protected void onPreExecute(){
super.onPreExecute();
progressBar= new ProgressDialog(getApplicationContext());
progressBar.setMessage("Loading...");
progressBar.show();
}
protected Long doInBackground(String... params) {
long someLong;
// do something here with params
// the Integer variable is used for progress
publishProgress(i);
// call it for example while downloading a file
return someLong;
}
// this is called whenever you call puhlishProgress(Integer)
protected void onProgressUpdate(Integer... progress) {
progressBar.incrementProgressBy(progress[0]);
}
// the onPostexecute method receives the return type of doInBackGround()
protected void onPostExecute(Long result) {
// do something with the result
progressBar.dismiss();
}
}
You said your problem was getting the Context. Well: Service is a Context
So you could simply make the AsyncTask an inner class of your Service and then use its Context.
I have two images in my drawable folder and I desire to alternate the two images in my view every x time.
I try to use a Asynctask but don't work and I can't found the solution.
My xml Code
<ImageView
android:id="#+id/imageload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="64dp"
android:adjustViewBounds="false"
android:baselineAlignBottom="false"
android:contentDescription="#string/imatge"
android:cropToPadding="false"
android:fitsSystemWindows="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#drawable/hdtitol2" />
I call the class with:
new ModifyImage().execute(null,null,null);
The main class contains de class with async code
public class ModifyImage extends AsyncTask<Void, Void, Void> {
ImageView img= (ImageView)findViewById(R.id.imageload);
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int i = 0;
boolean opt = true;
boolean exit = false;
while(!exit){
if(i == 1000){
i = 0;
if(!opt){
img.setImageResource(R.drawable.blackhdtitol2);
opt =true;
}else{
opt = false;
img.setImageResource(R.drawable.hdtitol2);
}
}
i++;
}
return null;
}
#Override
protected void onPostExecute(Void i){
}
}
Do this,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Integer tag = (Integer) img.getTag();
if(tag == R.drawable.blackhdtitol2){
img.setImageResource(R.drawable.blackhdtitol2);
img.setTag(R.drawable.blackhdtitol2);
}else{
img.setImageResource(R.drawable.hdtitol2);
img.setTag(R.drawable.hdtitol2);
}
}
}, 60*1000);
In the end I found a possible solution descarting all de java code that I had about this problem.
The solution that I found is to create a new class
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
public RepeatingThread() {
}
#Override
public void run() {
final ImageView img = (ImageView) findViewById(R.id.imageload);
if(img.getVisibility() == View.INVISIBLE ){
img.setVisibility(View.VISIBLE);
}else{
img.setVisibility(View.INVISIBLE);
}
mHandler.postDelayed(this, 1000);
}
}
And the code in the function on create:
final Thread t = new Thread(new RepeatingThread());
t.start();
I need to show a second activity after the progress bar is filled. I tried the code below but it doesn't show the progress bar and just shows my second activity.
This is the code:
public class MiSuper2 extends Activity {
String strListas[] = null;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
private StoreData stdArticulos = null;
public Cursor cursor = null;
private long fileSize = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
stdArticulos = new StoreData(this);
fileSize = 0;
setContentView(R.layout.main);
stdArticulos = new StoreData(this);
cursor = stdArticulos.leerArticulos();
mProgress = (ProgressBar) findViewById(R.id.progressbar_activity);
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
if(cursor.moveToFirst()) {
do{
strListas[cursor.getPosition()] = cursor.getString(cursor.getPosition());
}while(cursor.moveToNext());
}
Intent intent = new Intent(MiSuper2.this, PntArticulo.class);
startActivity(intent);
}
public int doWork() {
while (fileSize <= 1000000) {
fileSize++;
return (int) fileSize;
}
return 100;
}
}
This is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/imvLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/presentacion"
android:contentDescription="#string/logo"/>
<ProgressBar
android:id="#+id/progressbar_activity"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:layout_height="wrap_content" android:layout_marginTop="100dp"/>
</LinearLayout>
Please help
It looks like you are using the doWork() function to take up time so that you're progress bar does something. Even though you wrote a big loop, it still executes very quickly so you don't see your progress bar move. Rather, you want to simulate your Thread doing something computationally intensive by using Thread.sleep() which takes an argument that is the time to sleep in milliseconds.
Try changing your code to this:
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
try {
mProgressStatus += doWork();
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MiSuper2.this, Second.class));
}
});
}
}).start();
And...
public int doWork() throws InterruptedException {
Thread.sleep(1000);
return 1;
}
This will increment your progress bar by 1% every second. And finally, the documentation on Thread.sleep(): https://developer.android.com/reference/java/lang/Thread.html#sleep(long)
EDIT: Ramz beat me to this answer, but doesn't provide an explanation of why it's the answer. Hopefully my explanation helps.
EDIT2: I think you edited your questions since I started looking at it a second time. You had some errors in your XML before, but now it is gone. Regardless, your problem is now that you need the call to startActivity() inside your worker thread. Otherwise, the UI thread does not wait for the doWork() function to return and immediately starts the other Activity when your app starts. Sorry, I should have mentioned this before. The code I posted above is updated with this change.
Please try this code SplashScreen.java
package com.cud.point;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;
public class SplashScreen extends Activity {
ProgressBar bar;
TextView txt;
int total=0;
boolean isRunning=false;
// handler for the background updating
Handler handler=new Handler() {
#Override
public void handleMessage(Message msg) {
total=total+20;
String perc=String.valueOf(total).toString();
txt.setText(perc+"% completed");
bar.incrementProgressBy(20);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
bar=(ProgressBar)findViewById(R.id.progress);
txt=(TextView)findViewById(R.id.txt);
Handler x = new Handler();
x.postDelayed(new SplashHandler(), 5000);
}
class SplashHandler implements Runnable
{
public void run() {
// TODO Auto-generated method stub
startActivity(new Intent(getApplication(),YourSecound Activity.class));
SplashScreen.this.finish();
}
}
public void onStart() {
super.onStart();
// reset the bar to the default value of 0
bar.setProgress(0);
// create a thread for updating the progress bar
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<5 && isRunning;i++) {
// wait 100ms between each update
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
} } });
isRunning=true;
// start the background thread
background.start();
}
public void onStop() {
super.onStop();
isRunning=false;
}
}
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="15px" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Loading......" />
<TextView
android:id="#+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/splash" />
<ProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/imageView1"
android:max="100" />
</RelativeLayout>
this is an example of my project so please make necessary change in xml file
I have this code for the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="15px"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Loading..."
/>
<ProgressBar android:id="#+id/progressBar"
android:paddingTop="10px"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/txt"
/>
</LinearLayout>
Then for the class :
public class Loading extends Activity {
ProgressBar bar;
TextView txt;
int total=0;
boolean isRunning=false;
// handler for the background updating
Handler handler=new Handler() {
#Override
public void handleMessage(Message msg) {
total=total+5;
String perc=String.valueOf(total).toString();
txt.setText(perc+"% completed");
bar.incrementProgressBy(5);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_bar);
bar=(ProgressBar)findViewById(R.id.progressBar);
txt=(TextView)findViewById(R.id.txt);
}
public void onStart() {
super.onStart();
// reset the bar to the default value of 0
bar.setProgress(0);
// create a thread for updating the progress bar
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning;i++) {
// wait 1000ms between each update
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
}
}
});
isRunning=true;
// start the background thread
background.start();
}
public void onStop() {
super.onStop();
isRunning=false;
}
}
And with this I call it on another activity:
public void onClick (View v)
{
switch (v.getId())
{
case R.id.buttonNext3:
Intent Loading = new Intent(this, Loading.class);
startActivity(Loading);
getContent();
Call();
db.generation();
Intent Next3 = new Intent(this, FoodPlanning.class);
startActivity(Next3);
break;
}
}
But it is not work on mine, it just show blackscreen but it still on progress .... I want the loading bar appear when I click the button and the process still on progress. any idea? Thx u
As suggested by Adil, AsyncTask is the preferred method to run background tasks with easy options to run certain commands on the UI thread, while pushing the rest to the background. See this example from the SDK (http://developer.android.com/reference/android/os/AsyncTask.html):
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Note the "onProgressUpdate" method as well as the doInBackground.