Thursday, April 5, 2012

Android fiels downloading to the SD card from remote server:

Android fiels downloading to the SD card  from remote server:

TestActivity .java:
-----------------

public class TestActivity extends Activity implements MediaScannerConnectionClient {
    /** Called when the activity is first created. */

String   Url_str;
String[]               arr, title;
String filename;

MediaScannerConnection conn;
private ProgressDialog mProgressDialog;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
String filepath;
File                        storageDir , file;
final String STORAGE_PATH = "ODAC/";
DownloadHandler dh;
Thread downloadThread ;
private static Handler handler;
CharSequence text = "Hello toast!";
Context mContext;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        handler = new Handler();
        mContext = this;
         arr = new String[]
                {
some urls
};    
        title = new String[]
            {some names
           };          
     
        final List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        for(int i = 0; i < title.length; i++){
        final HashMap<String, String> map = new HashMap<String, String>();
            map.put("title", "" + title[i]);
            map.put("desc", "" + arr[i]);
            fillMaps.add(map);
        }
     
        final ListView list   = (ListView)findViewById(R.id.listview);
        SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.list, new String[]{"title"}, new int[] {R.id.list_free});
        list.setAdapter(adapter);
     
        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            @SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) list.getItemAtPosition(position);
           Toast.makeText(TestActivity.this, "ID '" + o.get("title") + "' was selected.", Toast.LENGTH_SHORT).show();                                                
           Url_str     = o.get("desc");
           filename = Url_str.substring(Url_str.lastIndexOf('/')+1, Url_str.length());
           text = filename + "  has dowloded .";
           file = new File(storageDir, filename);
           storageDir  = new File(Environment.getExternalStorageDirectory(), STORAGE_PATH);                      
           String file_extention = filename.substring((filename.lastIndexOf(".") + 1), filename.length());
           System.out.println(file_extention);
           String a = "mp3";
         
            if(file_extention.equals(a)){
            AlertDialog alertDialog = new AlertDialog.Builder(TestActivity.this).create();
           alertDialog.setTitle("                ");
           alertDialog.setMessage("download  /  play ");
           alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Download", new DialogInterface.OnClickListener()
           {
                 public void onClick(DialogInterface dialog, int which) {
                 if(!storageDir.exists()){
                      storageDir.mkdir();
                     }
                 if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
                  if(file.exists()){
                  handleFile(file);
                 }else{
                  dh = new DownloadHandler();
                  dh.downloadFile(getApplicationContext(), Url_str, filename);  
                 }            
                 }
                 else{
                    showMissingMediaDialog(TestActivity.this);
                 }
               
               } });
           alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Play", new DialogInterface.OnClickListener()
           {
                 public void onClick(DialogInterface dialog, int which) {
                Intent myIntent = new Intent(mContext,AudioViewController.class);
       myIntent.putExtra("URL",  "http://www.culture74.fr/images/agenda/son/");
       myIntent.putExtra("FileName", filename);
       startActivityForResult(myIntent, 0);
               } });
           alertDialog.show();
            }                                
            else{
               if(!storageDir.exists()){
                storageDir.mkdir();
               }
           if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
            if(file.exists()){
            handleFile(file);
           }else{
            dh = new DownloadHandler();
            dh.downloadFile(getApplicationContext(), Url_str, filename);  
           }            
           }
           else{
              showMissingMediaDialog(TestActivity.this);
           }
         //  System.out.println(downloadThread.isAlive());
         
            }
            }          
      });
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
               
    }//end of onCreate(-,-)    
   
 // Save the thread
@Override
public Object onRetainNonConfigurationInstance() {
return dh;
}

 
    public class DownloadHandler{
        /**
         * Downloads files in a separate thread.  Adds notification of download to status bar.
         * @param context - The current context
         * @param url - the URL to download
         * @param fileName - the name to save the file as
         */
        public void downloadFile(final Context context, final String url,final String fileName){          
            final int BUFFER_SIZE = 1024 * 23;
            final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context,context.getClass()), 0);

            // configure the notification
            final Notification notification = new Notification(R.drawable.download_icon, "Downloading " + fileName, System.currentTimeMillis());
            notification.flags = notification.flags |=Notification.FLAG_AUTO_CANCEL;
            notification.contentIntent = pendingIntent;
            notification.setLatestEventInfo(context, "Downloading file", "Downloading " + fileName, pendingIntent);

            final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(42, notification);
         
            downloadThread = new Thread() {
                public void run() {        
                    try{
                        //storageDir = new File(Environment.getExternalStorageDirectory(), STORAGE_PATH);
                        //if(!storageDir.exists()){
                        // storageDir.mkdir();
                        //}
                        File fileF = new File(storageDir, fileName);
                        //System.out.println(file.exists());
                        filepath = fileF.getPath();
                        URL urlObj = new URL(url);
                        URLConnection con = urlObj.openConnection();
                        //Log.d("MenuHandler.download", "length = " + length);
                        BufferedInputStream bis = new BufferedInputStream(con.getInputStream(), BUFFER_SIZE);

                        FileOutputStream fos = new FileOutputStream(fileF);
                        byte[] bArray = new byte[BUFFER_SIZE];
                        int current = 0;
                        int read = 0;
                        while(current != -1){
                            fos.write(bArray,0,current);
                            current = bis.read(bArray, 0, BUFFER_SIZE);
                            read = read + current;
                            //Log.d("DownloadHandler.download", "read = " + read);
                            //Log.d("DownloadHandler.download", "percent complete = " + complete);
                        }
                        //fos.flush();
                        fos.close();
                        bis.close();
                        notificationManager.cancel(42);
                     
                        if(conn!=null)
                        conn.disconnect();
            conn = new MediaScannerConnection(TestActivity.this,TestActivity.this);
               conn.connect();
               System.out.println(conn.isConnected());
                     
               handler.post(new MyRunnable());
                    }
                    catch(Exception ioe){
                        Log.d("DownloadHandler.download", "Error: " + ioe.toString(), ioe);
                    }
                }
            };
            downloadThread.start();
        }      
    }

    public static void showMissingMediaDialog(Context context){
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("No Sd_card");
        alertDialog.setMessage("The file cannot be downloaded because SD Card is not installed.  Please install SD Card and try again.");
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ok", new DialogInterface.OnClickListener()
        {
              public void onClick(DialogInterface dialog, int which) {
                  //do nothing      
            } });
        alertDialog.show();    
    }
 
 
    private void handleFile(final File dirOrFile) {
        //Log.d("FileBrowserActivity.browseTo()", "Called");
        if (dirOrFile.isDirectory() && !dirOrFile.getPath().endsWith("ODAC/")){
            this.file = dirOrFile;
        }
        else{              
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("alreay exist");
            alertDialog.setMessage("Replace file " + dirOrFile.getName() + "?");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener()
            {
                  public void onClick(DialogInterface dialog, int which) {
                 dh = new DownloadHandler();
         dh.downloadFile(getApplicationContext(), Url_str, filename);            
                } });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener()
            {
                  public void onClick(DialogInterface dialog, int which) {
                      //do nothing          
                } });
            alertDialog.show();
             
        }
    }
 
    public class MyRunnable implements Runnable {
public void run() {
System.out.println(text + "item. downloaded");
Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT).show();

}
}
 
   /* private void startDownload() {
        String url = Url_str;
        new DownloadFileAsync().execute(url);
    }
 
    class DownloadFileAsync extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
    @Override
    protected String doInBackground(String... aurl) {
    int count;
    try {
    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();

    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

    InputStream input = new BufferedInputStream(url.openStream());
    filename= aurl[0].substring(aurl[0].lastIndexOf('/')+1, aurl[0].length());
    OutputStream output = new FileOutputStream("/sdcard/" + filename);
    File SDCardRoot = Environment.getExternalStorageDirectory();
    File file = new File(SDCardRoot,filename);
    filepath = file.getPath();
    byte data[] = new byte[1024];
    long total = 0;
    while ((count = input.read(data)) != -1) {
    total += count;
    publishProgress(""+(int)((total*100)/lenghtOfFile) );
    output.write(data, 0, count);
    }
    output.flush();
    output.close();
    input.close();    
   
            if(conn!=null)
            conn.disconnect();
conn = new MediaScannerConnection(TestActivity.this,TestActivity.this);
   conn.connect();
   System.out.println(conn.isConnected());
 
    Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), 2);
 
    } catch (Exception e) {}
    return null;

    }
    protected void onProgressUpdate(String... progress) {
    Log.d("ANDRO_ASYNC",progress[0]);
    mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
   
    }
    }
 
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..\n" + (Url_str.substring(Url_str.lastIndexOf('/')+1, Url_str.length() )));
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
        }
    }*/
   
 
    @Override
    public void onMediaScannerConnected() {
        try{
            conn.scanFile(filepath, "*/*");
           } catch (java.lang.IllegalStateException e){
           }
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        conn.disconnect();
    }
 
}


AudioViewController.java:
---------------------------


public class AudioViewController extends Activity {
private String strURL = null;
private String strFileName = null;
private String strFileURL = null;
private String strAbsolutePath = null;
private VideoView mAudioView;
TextView textView;
Thread thread;
ProgressBar bar;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
    setContentView(R.layout.audioplayer);
    strURL = getIntent().getExtras().getString("URL");
    strFileName = getIntent().getExtras().getString("FileName");
    strFileURL = strURL + strFileName;
    mAudioView = (VideoView) findViewById(R.id.surface_view);
    textView       = (TextView) findViewById(R.id.text_kb_streamed);
    bar            = (ProgressBar)findViewById(R.id.progressBar1);
    textView.setText(strFileName  + "\n\t was selected");
    mAudioView.setMediaController(new MediaController(this));
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
 
    if(strFileURL == null || strFileURL.length() == 0){
    Toast.makeText(AudioViewController.this, "File URL/path is empty", Toast.LENGTH_LONG).show();
    }
    else{
    strAbsolutePath = Environment.getExternalStorageDirectory() + "Whagaa" + strFileName;
    File file = new File(strAbsolutePath);
   
    if(!file.exists()) {
    playVideoFromServer(strFileURL);
    bar.setVisibility((View.VISIBLE));
    textView.setText(strFileName  + "\n\t was buffring . . . ");
    thread = new Thread(){
public void run() {
try {
getDataSource(strFileURL, strFileName);
threadHandler.sendEmptyMessage(0);
}
    catch (Exception e) {
e.printStackTrace();
}    
}
};
    thread.start();    
    }
    else {
playVideoFromSDCARD(strAbsolutePath);
}
    }
}


/**
 * Play video from URL
 * @param url
 */
private void playVideoFromServer(String url) {
mAudioView.setVideoURI(Uri.parse(url));
         mAudioView.requestFocus();
         mAudioView.start();
}

/**
 * Play audio from SDCARD
 * @param url
 */
private void playVideoFromSDCARD(String filepath) {
mAudioView.setVideoURI(Uri.parse(filepath));
         mAudioView.requestFocus();
         mAudioView.start();
}

/**
* Buffer audio
* @param path
* @param filename
* @throws IOException
*/
private void getDataSource(String path, String filename) throws IOException {
if(isSDCARDMounted()){
if (!URLUtil.isNetworkUrl(path)) {
System.out.println("Invalid Path");
}
else
{
URI uri = null;
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();

if (stream == null) {
//throw new RuntimeException("stream is null");
}

uri = URI.create("file://"+Environment.getExternalStorageDirectory()+"/Whagaa/"+ strFileName);
System.out.println("URI: " + uri);
File file = new File(uri);
file.mkdirs();
file.delete();
file.createNewFile();

FileOutputStream fos = new FileOutputStream(file);
byte buf[] = new byte[128];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
fos.write(buf, 0, numread);

//textView.setText(strFileName  + "\n\t buffring...." + Integer.toString(count));
//count = count + 128;
} while (true);

boolean isRenamed = file.renameTo(new File(Environment.getExternalStorageDirectory()+"/Whagaa/"+filename));

if (isRenamed) {
           System.out.println("File was successfully renamed.\n");
       } else {
           System.out.println("File was not successfully renamed.\n");
       }

try {
stream.close();
}
catch (IOException ex) {
System.out.println(ex);
}
fos.flush();
fos.close();

}

}
else {
//Toast.makeText(AudioViewController.this, "SDCARD is not inserted", Toast.LENGTH_LONG).show();
}
}


/**
* Check if SDCARD inserted
* @return Yes/No
*/
private boolean isSDCARDMounted(){
return (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.d(this.getClass().getName(), "back button pressed");
AudioViewController.this.finish();
System.out.println(thread.isAlive());
}
return super.onKeyDown(keyCode, event);
}

private Handler threadHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            // whenever the Thread notifies this handler we have
            // only this behavior
        bar.setVisibility((View.GONE));
        textView.setText(strFileName + "\n \tbuffering has completed");
        }
    };
}



main.xml;
----------


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- list layout -->    
   <ListView android:id="@+id/listview" 
           android:layout_height="fill_parent"
           android:layout_width="fill_parent">
</ListView>
   <VideoView
   android:id="@+id/video_view"
   android:layout_width="wrap_content"
   android:layout_height="240dp" />
</LinearLayout>



listiyem.xml:
-----------
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView 
android:id="@+id/list_free" android:paddingTop="10dp" android:paddingBottom="10dp"
android:layout_height="wrap_content" 
android:layout_width="wrap_content"
android:text=""  android:typeface="serif"
android:textStyle="bold"
android:textSize="17dp"/>
</LinearLayout>



audioplayer.xml.xml:
--------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:padding="10dp">
<TextView   android:id="@+id/text_kb_streamed"
android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:textStyle="bold" android:textSize="20dp"
        android:text=""/>

<ProgressBar
   android:id="@+id/progressBar1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" 
   android:paddingTop="10dp"
   android:paddingLeft="100dp" />

<VideoView
   android:id="@+id/surface_view"
   android:layout_width="wrap_content"
   android:layout_height="240dp" />

</LinearLayout>

animation.xml;-




--------------


<?xml version="1.0" encoding="UTF-8"?>
<animation-list
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:oneshot="false">
    <item android:drawable="@drawable/stat_sys_download_anim0" android:duration="200" />
    <item android:drawable="@drawable/stat_sys_download_anim1" android:duration="200" />
    <item android:drawable="@drawable/stat_sys_download_anim2" android:duration="200" />
    <item android:drawable="@drawable/stat_sys_download_anim3" android:duration="200" />
    <item android:drawable="@drawable/stat_sys_download_anim4" android:duration="200" />
    <item android:drawable="@drawable/stat_sys_download_anim5" android:duration="200" />
</animation-list>




No comments: