Using an AsyncTask inside a Service Class?

后端 未结 3 535
闹比i
闹比i 2021-01-06 02:29

I have to upload data to a server. I am using a service that is running on the same process as my application. Should I use a Separate thread for upload process or Should I

相关标签:
3条回答
  • 2021-01-06 02:58

    Use AsyncTask in a service in android

    package ​com.emergingandroidtech.Services;
    
    import ​android.app.Service;
    
    import​ android.content.Intent;
    
    import​ android.os.IBinder;
    
    import ​android.util.Log;
    
    import​ android.widget.Toast;
    
    import​ java.net.MalformedURLException;
    
    import​ java.net.URL;
    
    import android.os.AsyncTask;
    
    public​ class ​MyService ​extends​ Service​
    
    {
    
    ​​​​@Override
    
    ​​​​public​ IBinder ​onBind(Intent​ arg0)​
    
    {
    
    ​​​​​​​​return ​null;
    
    ​​​​}
    
    ​​​​
    
    @Override ​
    
    ​​​public​ int ​onStartCommand(Intent ​intent,​int​ flags,​int ​startId)​
    
    {
    
    ​​​​​​​​
    
    //​We​ want ​this ​service ​to ​continue ​running ​until​ it ​is ​explicitly
    
    ​​​​​​​​//​stopped,​so​ return ​sticky. ​​​​​​​​
    
    Toast.makeText(this,​“Service​Started”,​Toast.LENGTH_LONG).show();
    
    ​​​​​​​​try
    
    {
    
    ​​​​​​​​​​​​new DoBackgroundTask().execute(
    
    ​​​​​​​​​​​​​​​new URL(“http://www.google.com/somefiles.pdf”),
    
    ​​​​​​​​​​​​​​​​​​​​new URL(“http://emergingandroidtech.blogspot.in”)); ​​​​​​​​
    
    }
    
    catch (MalformedURLException e)
    
    {
    
    ​​​​​​​​​​​​e.printStackTrace();
    
    ​​​​​​​​}
    
    ​​​​​​​​return ​START_STICKY; ​
    
    ​​​}
    
    ​​​​
    
    @Override
    
    ​​​​public ​void ​onDestroy()
    
    ​{
    
    ​​​​​​​​super.onDestroy();
    
    ​​​​​​​​Toast.makeText(this,​“Service​Destroyed”,​Toast.LENGTH_LONG).show(); ​​​
    
    ​} ​​​​
    
    ​​​​private ​int ​DownloadFile(URL​ url)
    
    ​{
    
    ​try​
    
    {
    
    ​​​​​​​​​​​​//---simulate​ taking ​some​time ​to ​download ​a​ file--- ​​​​​​​​​​​​
    
    Thread.sleep(5000);
    
    ​​​​​​​​}
    
    ​catch​(InterruptedException ​e)​
    
    {
    
    ​​​​​​​​​​​​e.printStackTrace(); ​
    
    ​​​​​​​}
    
    ​​​​​​​​//---return ​an ​arbitrary ​number​ representing ​
    
    ​​​​​​//​the ​size​ of ​the ​file ​downloaded--- ​
    
    ​​​​​​​return​ 100; ​
    
    ​​​}
    
    ​​​​
    
    private class DoBackgroundTask extends AsyncTask<URL, Integer, Long>
    
    {
    
    ​​​​​​​​protected Long doInBackground(URL... urls)
    
    {
    
     ​​​​​​​​​​​​int count = urls.length;
    
    ​​​​​​​​​​​​long totalBytesDownloaded = 0;
    
    ​​​​​​​​​​​​for (int i = 0; i < count; i++)
    
    {
    
    ​​​​​​​​​​​​​​​​totalBytesDownloaded += DownloadFile(urls[i]);
    
    ​​​​​​​​​​​​​​​​//---calculate percentage downloaded and
    
    ​​​​​​​​​​​​​​​​// report its progress--- ​
    
    ​​​​​​​​​​​​​​​publishProgress((int) (((i+1) / (float) count) * 100)); ​
    
    ​​​​​​​​​​​}
    
    ​​​​​​​​​​​​return totalBytesDownloaded; ​​
    
    ​​​​​​}
    
    ​​​​​​​​
    
    protected void onProgressUpdate(Integer... progress)
    
    {
    
    ​​​​​​​​​​​​Log.d(“Downloading files”, ​​​​​​​​​​​​​​​​​​​​String.valueOf(progress[0]) + “% downloaded”); ​​​​​​​​​​​​
    
    Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​String.valueOf(progress[0]) + “% downloaded”, ​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show(); ​​​​​​​​
    
    }
    
    ​​​​​​​​
    
    protected void onPostExecute(Long result)
    
    {
    
    ​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“Downloaded “ + result + “ bytes”, ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show(); ​​
    
    ​​​​​​​​​​stopSelf();
    
    ​​​​​​​​} ​
    
    ​​​}
    
    } 
    

    Try this it may be work. Thank you.

    0 讨论(0)
  • 2021-01-06 03:00

    Yes you can, the below code will run every 5 seconds. Use your regular connection code for sending part.

    public class AsyncTaskInServiceService extends Service {
    
        public AsyncTaskInServiceService() {
            super("AsyncTaskInServiceService ");
        }
    
        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            final Timer t = new Timer();
            t.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    //Connect to database here
                    try {
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, 0, 5000);
        }
    }
    
    0 讨论(0)
  • 2021-01-06 03:05

    No problem to use AsyncTask in a service.

    NOTE / FIX : I was wrong when I said the service runs in background, it only applis to IntentService. As noted in the comments and in the documentation, a service does not create it's own thread :

    Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.

    That means you must use an AsyncTask (or another thread in any case) to perform your upload task.

    0 讨论(0)
提交回复
热议问题