Android download file by Service.

October 2, 2012   ·   0 Comments

Screen Shot 2012-10-02 at 1.47.09 PM

package com.powenko.tutorial_service_downloadservicemessenger;



import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {


        
        
  Messenger messenger = null;

  private Handler handler = new Handler() {
    public void handleMessage(Message message) {
      Bundle data = message.getData();
      if (message.arg1 == RESULT_OK && data != null) {
          String text = data.getString(DownloadServiceMessenger.RESULTPATH);
          String texturl = data.getString(DownloadServiceMessenger.URLPATH);
        Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
      }
    }
  };

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  }

  private ServiceConnection conn = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
      messenger = new Messenger(binder);

    }

    public void onServiceDisconnected(ComponentName className) {
      messenger = null;
    }
  };

  protected void onResume() {
    super.onResume();
    Toast.makeText(this, "OnResume called", Toast.LENGTH_SHORT).show();
    Intent intent = null;
    intent = new Intent(this, DownloadServiceMessenger.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(handler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, conn, Context.BIND_AUTO_CREATE);
  }

  @Override
  protected void onPause() {
    super.onPause();
    unbindService(conn);
  }

  public void onClick(View view) {
    Message msg = Message.obtain();

    try {
      Bundle bundle = new Bundle();
      bundle.putString(DownloadServiceMessenger.FILENAME, "index.html");
      bundle.putString(DownloadServiceMessenger.URLPATH, "http://www.vogella.com/index.html");
      msg.setData(bundle);
      messenger.send(msg);
    } catch (RemoteException e) {
      e.printStackTrace();
    }
  }
} 

package com.powenko.tutorial_service_downloadservicemessenger;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.StrictMode;
import android.util.Log;

public class DownloadServiceMessenger extends Service {
  public static final String FILENAME = "fileName";
  public static final String URLPATH = "urlPath";
  public static final String RESULTPATH = "urlPath";
  private int result = Activity.RESULT_CANCELED;

  // Used to receive messages from the Activity
  final Messenger inMessenger = new Messenger(new IncomingHandler());
  // Use to send message to the Activity
  private Messenger outMessenger;

  @TargetApi(9)
public DownloadServiceMessenger() {
    super();
    // Don't do this
    // Network Stuff will run in the main thread
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
  }

  class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
      Log.e("MESSAGE", "Got message");
      Bundle data = msg.getData();
      String urlPath = data.getString(DownloadServiceMessenger.URLPATH);
      String fileName = data.getString(DownloadServiceMessenger.FILENAME);
      String outputPath = download(urlPath, fileName);

      Message backMsg = Message.obtain();
      backMsg.arg1 = result;
      Bundle bundle = new Bundle();
      bundle.putString(RESULTPATH, outputPath);
      backMsg.setData(bundle);
      try {
        outMessenger.send(backMsg);
      } catch (android.os.RemoteException e1) {
        Log.w(getClass().getName(), "Exception sending message", e1);
      }
    }
  }

  private String download(String urlPath, String fileName) {
    File output = new File(Environment.getExternalStorageDirectory(),
        fileName);
    if (output.exists()) {
      output.delete();
    }

    InputStream stream = null;
    FileOutputStream fos = null;
    try {

      URL url = new URL(urlPath);
      stream = url.openConnection().getInputStream();
      InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
      fos = new FileOutputStream(output.getPath());
      int next = -1;
      while ((next = reader.read()) != -1) {
        fos.write(next);
      }
      // Sucessful finished
      result = Activity.RESULT_OK;

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return output.getAbsolutePath();

  }

  @Override
  public IBinder onBind(Intent intent) {
    Bundle extras = intent.getExtras();
    // Get messager from the Activity
    if (extras != null) {
      outMessenger = (Messenger) extras.get("MESSENGER");
    }
    // Return our messenger to the Activity to get commands
    return inMessenger.getBinder();
  }
} 
shareShare on FacebookShare on Google+Share on LinkedInEmail this to someonePrint this pageBuffer this pageDigg thisFlattr the authorShare on RedditPin on PinterestShare on StumbleUponShare on TumblrTweet about this on Twitter

By


Readers Comments (0)


You must be logged in to post a comment.

PowenKo’s Online Store

powenko_arduinoBook
Android7

Amazon

adsbygoogle

Recent Posts

Categories

Amazon