Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the service object inside activities?

This the code of my service:

public class DownloadService extends Service {
    LocalBroadcastManager mLocalBroadcastManager;
    ArrayList<DownloadAsyncTask> dat = new ArrayList<DownloadAsyncTask>();
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onStart( Intent intent, int startId ) {
          super.onStart( intent, startId );
          Log.d("service","DownloadService started");
    }
    public void startDownload(String url, String fname, ProgressBar pBar){
        int dID = dat.size();
        Log.d("status","dat length:"+dID);
        dat.add( new DownloadAsyncTask(url,fname,pBar));
        dat.get(dID).execute();
    }

    public void cancelDownload(String fname){
        for(DownloadAsyncTask da: dat){
            if(da.getName().equals(fname)){
                da.cancel(true);
            }
        }
    }

    public DownloadAsyncTask getDownloadByName(String fname){
        for(DownloadAsyncTask da: dat){
            if(da.getName().equals(fname)){
                return da;
            }
        }
        return null;
    }
    public ArrayList<DownloadAsyncTask> getAllDownloads(){
        return dat;
    }
    public class DownloadAsyncTask extends AsyncTask<String, Integer, String>{
        ProgressBar progressBar;
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/com.ms.rightel.store/");
        int percentage = 0;
        static final int DOWNLOAD_STATUS_FINISHED = 1;
        static final int DOWNLOAD_STATUS_RUNNING = 0;
        static final int DOWNLOAD_STATUS_FAILED = -1;
        static final int DOWNLOAD_STATUS_PAUSED = 2;
        int status = DOWNLOAD_STATUS_RUNNING;
        double fileSize = 0;
        String downloadUrl,fileName;

        public DownloadAsyncTask(String url, String fname, ProgressBar pBar){
            downloadUrl = url;
            fileName = fname;
            progressBar = pBar;
        }
        public String getName(){
            return fileName;
        }
        public void replaceProgressBar(ProgressBar pBar){
            progressBar = pBar;
        }

        private boolean checkDirs(){
            if(!dir.exists()){
                return dir.mkdirs();
            }
            return true;
        }
        public int getDownloadStatus(){
            return status;
        }
        private long isIncomplete(){
            File from = new File(dir,fileName+"-incomplete");
            if(from.exists()){
                Log.d("status","download is incomplete, filesize:" + from.length());
                return from.length();
            }
            return 0;
        }

        @Override
        protected String doInBackground(String... params) {
                //fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1);
                if(!checkDirs()){
                    return "Making directories failed!";
                }
                try {
                    byte[] buffer = new byte[500];
                    int bufferLength = 0;
                    double downloadedSize = 0;
                    URL url = new URL(downloadUrl);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(10000);
                    urlConnection.setReadTimeout(10000);
                    //Log.d("status","ReadTimeOut: "+urlConnection.getReadTimeout() + "ConnectTimeOut: "+urlConnection.getConnectTimeout());
                    long downloaded = isIncomplete();
                    if(downloaded > 0){
                        urlConnection.setRequestProperty("Range", "bytes="+(downloaded)+"-");
                        downloadedSize = downloaded;
                        fileSize = downloaded;
                    }
                    urlConnection.setDoOutput(true);
                    urlConnection.connect();
                    fileSize += urlConnection.getContentLength();
                    FileOutputStream fos = new FileOutputStream(new File(dir,fileName+"-incomplete"),true);
                    InputStream inputStream = urlConnection.getInputStream();
                    while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
                    {
                        if(isCancelled()){
                            break;
                        }
                        fos.write(buffer, 0, bufferLength);
                        downloadedSize += bufferLength;
                        percentage = (int) ((downloadedSize / fileSize) * 100);
                        publishProgress(percentage);
                        //Log.d("status","downloading: " + downloadedSize+"/"+fileSize+" ("+percentage+"%)");
                    }
                    fos.close();
                    urlConnection.disconnect();
                } catch (Exception e) {
                    Log.e("Download Failed","Error: " + e.getMessage());
                    return "Download failed";
                }
                if(isCancelled()){
                    return "Download cancelled";
                }
            return "Download complete";
        }
        @Override
        protected void onProgressUpdate(Integer... values){
            super.onProgressUpdate(values[0]);
            if(progressBar != null){
                progressBar.setProgress(values[0]);
            }else{
                Log.w("status", "ProgressBar is null, please supply one!");
            }
        }

        @Override
        protected void onPreExecute(){
            mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_STARTED"));
        }

        @Override
        protected void onPostExecute(String str){
            if(str.equals("Download complete")){
                File from = new File(dir,fileName+"-incomplete");
                File to = new File(dir,fileName);
                from.renameTo(to);
                mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_FINISHED"));
            }
            if(str.equals("Download failed")){
                mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_FAILED"));
            }
        }

        @Override
        protected void onCancelled(){
            mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_CANCELLED"));
        }

    }

}

I'm using this service to manage multiple downloads. Now I need to access this service object inside different activities in order to be able to add to downloads or get the list of currently running downloads. How can I do this?

like image 971
2hamed Avatar asked Jun 24 '12 13:06

2hamed


People also ask

How do I start a service from activity?

A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. A service is bound when an application component binds to it by calling bindService().

How send data from service to activity in Android?

class MainActivity : AppCompatActivity() { private val sb = object :SerToBroad(){ override fun broadcastResult(connected: String?) { t(connected) } } override fun onCreate(savedInstanceState: Bundle?) { super. onCreate(savedInstanceState) setContentView(R. layout. activity_main) } fun t(connected: String?) { Toast.


1 Answers

Well, I got it done through the use of singletones. I added a static variable to the class which is intialized by null. Then inside onStart method I assign the current instance of the class to this static variable and then use a static method to return the actual object.

private static DownloadService self = null;
public static DownloadService getServiceObject(){
    return self;
}
@Override
public void onStart( Intent intent, int startId ) {
   super.onStart( intent, startId );
   self = this;
}
like image 62
2hamed Avatar answered Nov 16 '22 23:11

2hamed