Main UI freezes even when tasks are handled by AsyncTask - android

I made Service that runs on the background collecting data from internet using AsyncTask and storing them in Shared Preferences. Even though the work is done in AsyncTask it still freezes my main activity.
Here is the code for Service:
public class GetterService extends Service {
SharedPreferences.Editor editor;
HashMap<Integer,String> links = new HashMap<Integer,String>();
#Override
public void onCreate() {
editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
populateLinks();
}
private void populateLinks(){
// Here I add links to HashMap
}
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "GetterService ON BIND", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "GetterService ON DESTROY", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
doTasks();
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this, "GetterService ON UNBIND", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
private void doTasks(){
for (Integer in : links.keySet()) {
Document doc = null;
try {
doc = new NetTask().execute(links.get(in)).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (doc != null) {
Elements names = doc.select("strong, li");
if(names != null && names.size() > 0) {
for (int j = 0; j < names.size(); j++) {
editor.putString("header"+j, names.get(j).text().toString());
}
}
editor.commit();
}
}
}
public class NetTask extends AsyncTask<String, Integer, Document>
{
#Override
protected Document doInBackground(String... params)
{
Document doc = null;
try {
doc = Jsoup.connect(params[0]).timeout(5000).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
}
}
and here is how I start the service from main activity:
Intent startServiceIntent = new Intent(this, GetterService.class);
this.startService(startServiceIntent);

Even though the work is done in AsyncTask it still freezes my main activity.
You are using get():
doc = new NetTask().execute(links.get(in)).get();
And get() blocks the UI thread until the AsyncTask has completed, to me this method defeats the purpose of using a AsyncTask...
You should move this logic:
if (doc != null) {
Elements names = doc.select("strong, li");
if(names != null && names.size() > 0) {
for (int j = 0; j < names.size(); j++) {
editor.putString("header"+j, names.get(j).text().toString());
}
}
editor.commit();
}
Inside your NetTask's onPostExecute() method and remove get(). Now your AsyncTask won't bind-up the main thread.

It's because of the
new NetTask().execute(links.get(in)).get();
call.
AsyncTask.get() blocks until the async call has been completed. To be asynchronous you need to implement
onPostExecute()
and process the results there.

Don't call get(), just call execute(). Implement and overridden onPostExecute() to take a Document object as a parameter. onPostExecute() is called automatically when doInBackground() returns. Code in onPostExecute() is executed on the UI thread, so you can interact with the UI that way.
I suggest you take a look at the AsyncTask section in this document, http://developer.android.com/guide/components/processes-and-threads.html and the AsyncTask API page here, http://developer.android.com/reference/android/os/AsyncTask.html.

I had the similar problem and figured out what's going on. This code will not freeze UI, but if you put 'for loop' and sleep inside onProgressUpdate, then UI will be frozen during the process.
public class Karaoke extends AsyncTask<Void, Integer, Void> {
private Handler mHandler = new Handler(Looper.getMainLooper());
protected Void doInBackground(Void... urls) {
animating = true;
{
for (int i = 0;i < 6; i++)
{
publishProgress(i);
try
{
Thread.sleep(1000);
publishProgress(i);
}
catch (Exception xx){
}
}
}
animating = false;
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
if (light)
{
light = false;
iv_array[findview(egtxts[values[0]].getText() + "")].setImageResource(onpress);
}
else
{
light = true;
iv_array[findview(egtxts[values[0]].getText() + "")].setImageResource(onup);
}
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}

Related

Android ASyncTask Crashing on Android 4 and below

I am using ASyncTask to do simple animation in my app. But it only works on Android 5.0+, below that it just crashes and says that I edit UI from the wrong thread. Here is my code:
private class AlphaCorrect extends AsyncTask<Integer, Integer, Integer> {
float alpha;
#Override
protected Integer doInBackground(Integer[] params) {
Log.i("back","running");
for (float i = 0.0f; i < 0.9; i += 0.02) {
alpha = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Update();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (float i = 0.8f; i > -0.1f; i -= 0.02) {
alpha = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Update();
}
return null;
}
#Override
protected void onPreExecute() {
Log.i("run", "RUN");
canClick = false;
}
#Override
protected void onPostExecute(Integer result) {
canClick = true;
}
protected void Update() {
correct.setAlpha(alpha);
}
}
I tried Runnable, Thread and some other things already. Any ideas?
You do exactly what the error says - you update UI from another thread. Override onProgressUpdate method of AsyncTask, put Update() inside it and call publishProgress(0) in your doInBackground method
you can not edit any ui of the activity from the do in background of any asynctask. thats why you are getting this error. the values you can edit from the doinbackground is local verables and global veriables.
you can not edit the ui from doInBackground().
the sloution would be to use onProgressUpdate() and do the ui changes in the onpogressupdate() .
let me know if this is what you want.
it just like their say.you cann't update anything in your Update(), you should use the onProgressUpdate(),this method provide by AsynTask.

how to automatically invoke a method in android?

im building an android application that recive images from arduino uno in order to show them continously as a video , i write an asyncTask that reads image and show it in image view , how can i invoke this method every seconed automatically .
here is my asyncTask
I made a button that invoke the async task , but how to make it invoked continously
class myAsyncTask extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
mmInStream = tmpIn;
int byteNo;
try {
byteNo = mmInStream.read(buffer);
if (byteNo != -1) {
//ensure DATAMAXSIZE Byte is read.
int byteNo2 = byteNo;
int bufferSize = 7340;
int i = 0;
while(byteNo2 != bufferSize){
i++;
bufferSize = bufferSize - byteNo2;
byteNo2 = mmInStream.read(buffer,byteNo,bufferSize);
if(byteNo2 == -1){
break;
}
byteNo = byteNo+byteNo2;
}
}
}
catch (Exception e) {
// TODO: handle exception
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
bm1 = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
image.setImageBitmap(bm1);
}
}
If it's from a background thread, one possibility is to use an unbounded for loop. For example, suppose the AsyncTask currently does:
private class MyTask extends AsyncTask<T1, Void, T3>
{
protected T3 doInBackground(T1... value)
{
return longThing(value);
}
protected void onPostExecute(T3 result)
{
updateUI(result);
}
}
then rewrite it as something like:
private class MyTask extends AsyncTask<T1, T3, T3>
{
protected T3 doInBackground(T1... value)
{
for (;;)
{
T3 result = longThing(value);
publishProgress(result);
Thread.sleep(1000);
}
return null;
}
protected void onProgressUpdate(T3... progress)
{
updateUI(progress[0]);
}
}
Of course, you should have a check to break the loop (for example when the Activity is paused or destroyed).
Another option is to create a Handler instance and call postDelayed() repeatedly.
Handler h = new Handler();
h.postDelayed(r, DELAY_IN_MS);
Runnable r = new new Runnable() {
public void run() {
// Do your stuff here
h.postDelayed(this, DELAY_IN_MS);
}
}

How to perform background process in android?

I am performing some operations(uploading image to webservice) in IntentService.
Please see my code below.
Inside the activity i am calling service like this.
I am calling the below method after capturing the image i.e. inside onActivityResult. The app is getting hanged when i call this method in onActivityResult. I am able to perform the task in IntentService. But the acitivity is getting hanged.
private void callService(){
Intent intent = new Intent(this, TestIntentService.class);
intent.putExtra("imageData", imageData);
startService(intent);
}
This is my IntentService Class.
Can i perform webservice call inside callImageUploadAPI().
Am i doing anything wrong here?
public class TestIntentService extends IntentService {
public TestIntentService() {
super("com.screens.testapp");
// TODO Auto-generated constructor stub
}
//imageData passed from the activity
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if(intent != null){
Bundle extras = intent.getExtras();
imageData= extras.getString("imageData");
}
callImageUploadAPI(imageData);
}
private void callImageUploadAPI(final String imageData) {
// TODO Auto-generated method stub
try {
if (Log.checkNetworkStatus(TestIntentService.this)) {
} else {
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
Thanks
If you need to do a task in background, Android provides a class called AsyncTask which you can extend and use it for doing a network operation or any other heavy operation. This is an example from Android Developer Website (AsyncTask Page):
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));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
This may be used in your code this way:
if (Log.checkNetworkStatus(TestIntentService.this)) {
new DownloadFilesTask().execute(url1, url2, url3);
} else {
}
For you to perform actions in the background use Services.
You can launch the services from your activity and you can assign a thread for the service and a handler for communication from that thread to the UIThread.
Check this: http://developer.android.com/guide/components/services.html
A little sneak peek
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

Android - Call an Asynctask from an Asynctask with infinity loop

I have 2 Asynctask, 1 for get data (location) from server then set a marker on map with this location and another call 1st Asyntask in a loop for updating location.
Here my code:
public class AsynComp extends AsyncTask<Void, Void, Void> {
ProgressDialog taxiDialog;
#Override
protected Void doInBackground(Void... params) {
jsonComp = new JSONComp(find_url);
find_status = jsonComp.getJsonStatus(txt_search);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (find_status.equals("2013")) {
Toast.makeText(getBaseContext(), "no result",
Toast.LENGTH_SHORT).show();
} else if (find_status.equals("2012")) {
for (Marker marker:markers){
if(marker.getTitle().equals(compFollow)){
marker.remove();
}
}
for (int i=0; i<number;i++){
comp = new Comp(jsonComp.getJsondata(i));
SetMarkerComp(comp);
try {
Thread.sleep(1400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class AsynFollow extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (!taxiFollow.equals("")) {
number = 1;
txt_search = compFollow;
find_url = "http://192.111.125.80:8001/Default.aspx?username="
+ Id + "&password=" + Pass + "&sohieuxe="+txt_search;
while (!stop){
new AsynComp().execute();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
taxiFollow = "";
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!compFollow.equals("")) {
Toast.makeText(getBaseContext(), "Follow "+compFollow, Toast.LENGTH_SHORT).show();
} else {
iv_theodoi.setVisibility(View.VISIBLE);
iv_theodoif.setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Plz choose a marker", Toast.LENGTH_SHORT).show();
}
}
}
And i have 2 buuton, 1 to call AsynFollow.execute(), another to stop it.
This code can run but app will force close after awhile.
Any solution? thanks.
P/s: i'm a newbie in android.
You shoulnd you asyncTask for this. For repetitive action, like changing status in some interval, use Timer class. In this way you can implement repetitive action which can be repeated in intervals.
In this way you can stop this time by on click listener. You can run two times and specify it's realtions using other variables.
If you're newbe, you should read about multitasking in Android: Timer, AsyncTask, Handler.
In my opinion this docs will tell you much more than thousands of comments in stackoverflow.

Determine that thread is running or not if using runnable in android

I have created a program in android for multithreading.
When I hit one of the button its thread starts and print value to EditText now I want to determine that thread is running or not so that I can stop the thread on click if it is running and start a new thread if it is not running here is mu code:
public void startProgress(View view) {
final String v;
if(view == b1)
{
v = "b1";
}
else
{
v = "b2";
}
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
//for (int i = 0; i <= 10; i++) {
while(true){
if(v.equals("b1"))
{
i++;
}
else if(v.equals("b2"))
{
j++;
}
try {
if(v.equals("b1"))
{
Thread.sleep(3000);
}
else if(v.equals("b2"))
{
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
// progress.setProgress(value);
if(v.equals("b1"))
{
String strValue = ""+i;
t1.setText(strValue);
}
else
{
String strValue = ""+j;
t2.setText(strValue);
}
//t1.setText(value);
}
});
}
}
};
new Thread(runnable).start();
}
#Override
public void onClick(View v) {
if(v == b1)
{
startProgress(b1);
}
else if(v == b2)
{
startProgress(b2);
}
}
Instead of that messy code, an AsyncTask would do the job you need with added readability ...
It even has a getStatus() function to tell you if it is still running.
You'll find tons of examples by looking around a bit (not gonna write one more here). I'll simply copy the one from the documentation linked above:
Usage
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
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));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
Use a static AtomicBoolean in your thread and flip its value accordingly. If the value of the boolean is true, your thread is already running. Exit the thread if it is true. Before exiting the thread set the value back to false.
There are some way can check the Thread properties
You able to check Thread is Alive() by
Thread.isAlive() method it return boolean.
You able to found runing thread run by
Thread.currentThread().getName()
Thanks

Categories

Resources