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 ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.