IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Android Discussion :

Télecharger un fichier à partir dun serveur


Sujet :

API standards et tierces Android

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2013
    Messages
    37
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2013
    Messages : 37
    Points : 33
    Points
    33
    Par défaut Télecharger un fichier à partir dun serveur
    Bonjour

    Je suis entrain de developper une application android similaire a google drive une parmi ses fonctionnalites est de telecharger un fichier du serveur vers mon smartphone.Pour ce faire jai utilise les fonctions suivantes que je l ai pris d un projet exsistant sur github
    Method for the download notifier :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    public void notificationDownload() {
     
      isDownload = false;
      try {
     
     
      notificationManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
      String MyText = "Telechargement";
      titleText = URLDecoder.decode(fileName);
      notiText = "Téléchargement en cours...";
     
      Log.d("Download file name ",fileName + " <=======");
      notification = new Notification(R.drawable.icon, MyText,
        System.currentTimeMillis());
     
      Intent MyIntent = new Intent(Intent.ACTION_VIEW);
     
      MyIntent.putExtra("extendedTitle", titleText);
     
      PendingIntent StartIntent = PendingIntent.getActivity(
        getApplicationContext(), 0, MyIntent, 0);
      notification.setLatestEventInfo(getApplicationContext(), titleText,
        notiText, StartIntent);
     
      notificationManager.notify(NOTFICATION_ID, notification);
     
     
      Intent i = new Intent(getApplicationContext(), Downloader.class);
      Log.v(TAG, "you are entring to download a file");
      i.setData(Uri.parse(mFileUrl));
      Log.v(TAG, "step1");
      i.putExtra(Downloader.EXTRA_MESSENGER, new Messenger(notiHandler));
      Log.v(TAG, "step2");
      startService(i);
      Log.v(TAG, "step3");
     
    }
      catch (Exception e){
       Log.v(TAG, "probleme de telechargement://"+e);
      }
     }
    et pour la classe du telechargemet :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
     
     
    public class Downloader extends IntentService {
      public static final String EXTRA_MESSENGER="com.cloud.downloadmanager.downloader.EXTRA_MESSENGER";
      private HttpClient client=null;
     
      Intent i;
     
      public Downloader() {
        super("Downloader");
      }
     
      @Override
      public void onCreate() {
        super.onCreate();
     
        client=new DefaultHttpClient();
      }
     
      @Override
      public void onDestroy() {
        super.onDestroy();
     
        client.getConnectionManager().shutdown();
      }
     
      @Override 
      public void onHandleIntent(Intent i) {
       downloadFile(i);
      }
     
     
      Thread download = new Thread() {
     
          @Override
          public void run() {
     
              for (int i = 1; i < 100; i++) {
               DashBoardActivity.updateNotation();
     
                  try {
                      Thread.sleep(100);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
     
              Bundle extras=i.getExtras();
     
          if (extras!=null) {
            Messenger messenger=(Messenger)extras.get(EXTRA_MESSENGER);
            Message msg=Message.obtain();
     
            msg.arg1=Activity.RESULT_OK;
     
            try {
              messenger.send(msg);
            }
            catch (android.os.RemoteException e1) {
              Log.w(getClass().getName(), "Exception sending message", e1);
            }
          }
     
     
          }
      };
     
     
      public void downloadFile(Intent i) {
       if(isOnline()) {
        String url = i.getData().toString();
       GetMethod gm = new GetMethod(url);
     
       try {
        int status = BaseActivity.httpClient.executeMethod(gm);
    //    Toast.makeText(getApplicationContext(), String.valueOf(status),2).show();
        Log.e("HttpStatus","==============>"+String.valueOf(status));
        if (status == HttpStatus.SC_OK) {
         InputStream input = gm.getResponseBodyAsStream();
     
         String fileName = new StringBuffer(url).reverse().toString();
         String[] fileNameArray = fileName.split("/");
         fileName = new StringBuffer(fileNameArray[0]).reverse()
           .toString();
     
         fileName = URLDecoder.decode(fileName);
         File folder = new File(
           BaseActivity.mDownloadDest);
         boolean success = false;
         if (!folder.exists()) {
          success = folder.mkdir();
         }
         if (!success) {
          // Do something on success
          File file = new File(BaseActivity.mDownloadDest, fileName);
          OutputStream fOut = new FileOutputStream(file);
     
          int byteCount = 0;
          byte[] buffer = new byte[4096];
          int bytesRead = -1;
     
          while ((bytesRead = input.read(buffer)) != -1) {
           fOut.write(buffer, 0, bytesRead);
           byteCount += bytesRead;
    //       DashBoardActivity.updateNotation();
          }
     
          fOut.flush();
          fOut.close();
         } else {
          // Do something else on failure
          Log.d("Download Prob..", String.valueOf(success)
            + ", Some problem in folder creating");
         }
     
        }
       } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
       gm.releaseConnection();
     
       Bundle extras=i.getExtras();
     
          if (extras!=null) {
            Messenger messenger=(Messenger)extras.get(EXTRA_MESSENGER);
            Message msg=Message.obtain();
     
            msg.arg1=Activity.RESULT_OK;
     
            try {
              messenger.send(msg);
            }
            catch (android.os.RemoteException e1) {
              Log.w(getClass().getName(), "Exception sending message", e1);
            }
          }
       } else {
        WebNetworkAlert();
       }
      }
      public boolean isOnline() {
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo netInfo = cm.getActiveNetworkInfo();
     
      if (netInfo != null && netInfo.isConnectedOrConnecting()) {
       // Try This
       int i = netInfo.getType();
       System.out.println("Net Type =" + i);
     
       return true;
      }
      return false;
     
     }
     
     public void WebNetworkAlert() {
      new AlertDialog.Builder(this).setTitle("Network Error")
        .setMessage("Internet connection not available.")
        .setPositiveButton("Ok", new OnClickListener() {
         public void onClick(DialogInterface arg0, int arg1) {
          // do stuff onclick of YES
    //      finish();
          return;
         }
        }).show();
     }
     
    }

  2. #2
    Membre actif
    Homme Profil pro
    Développeur Java / C++
    Inscrit en
    Mars 2013
    Messages
    128
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Java / C++

    Informations forums :
    Inscription : Mars 2013
    Messages : 128
    Points : 228
    Points
    228
    Par défaut
    Bonjour silverTwist,

    Quel est la question ou le problème rencontré?
    Pensez à lire les règles du forum avant de poster.

    Si un poste ou un commentaire vous a été utile, merci de mettre un petit !
    Problème résolu? alors pensez à cliquer sur .
    Si vous avez trouvé la solution tout seul, merci de la poster, ça pourrait aider les suivants!

    Bonjour, s'il vous plaît et merci => ses mots ne coûtent rien, mais ils font toujours plaisirs!

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2013
    Messages
    37
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2013
    Messages : 37
    Points : 33
    Points
    33
    Par défaut
    mon problème est que le téléchargement ne fonctionne pas. Je pense que peut-être le problème est ici :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    Intent i = new Intent(getApplicationContext(), Downloader.class);
      Log.v(TAG, "you are entring to download a file");
      i.setData(Uri.parse(mFileUrl));
      Log.v(TAG, "step1");
      i.putExtra(Downloader.EXTRA_MESSENGER, new Messenger(notiHandler));
      Log.v(TAG, "step2");
      startService(i);
      Log.v(TAG, "step3");
    Ce code n'affiche pas aucune erreur mais je n'ai aucune idee pour quoi le telechargement ne se deroule pas

  4. #4
    Membre actif
    Homme Profil pro
    Développeur Java / C++
    Inscrit en
    Mars 2013
    Messages
    128
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Java / C++

    Informations forums :
    Inscription : Mars 2013
    Messages : 128
    Points : 228
    Points
    228
    Par défaut
    Le code est plutôt bien fait, et les log sont assez présent, donc regardez dans le LogCat, sur les logs "debug" (Log.d) ou "verbose" (Log.v). Mettez aussi des points d'arrêt si besoin, pour vérifier le contenue d'une variable.

    Cela peut venir de l'url que vous donnez au downloader peut-être?
    Pensez à lire les règles du forum avant de poster.

    Si un poste ou un commentaire vous a été utile, merci de mettre un petit !
    Problème résolu? alors pensez à cliquer sur .
    Si vous avez trouvé la solution tout seul, merci de la poster, ça pourrait aider les suivants!

    Bonjour, s'il vous plaît et merci => ses mots ne coûtent rien, mais ils font toujours plaisirs!

  5. #5
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2013
    Messages
    37
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2013
    Messages : 37
    Points : 33
    Points
    33
    Par défaut
    Tout cela est deja fait mais je n'arrive pas a comprendre pour quoi je n'arrive pas a telecharger les fichiers ???

  6. #6
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Personellement je ne comprends pas trop:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    for (int i = 1; i < 100; i++) {
               DashBoardActivity.updateNotation();
     
                  try {
                      Thread.sleep(100);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
    (Thread.sleep() = erreur quelque part)
    Enfin bref, je ne vois pas du tout l'interêt du thread "download"....

    Ensuite, le service crée son client ('client')
    puis délègue les connections à BaseActivity.httpClient ?
    Pas sur que BaseActivity existe (ca sent le NullPointerException).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Log.e("HttpStatus","==============>"+String.valueOf(status));
    Pourquoi e ? il n' y a pas d'erreur/exception.... ce devrait être simplement:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Log.i("Downloader","HttpStatus is "+status);
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
         String fileName = new StringBuffer(url).reverse().toString();
         String[] fileNameArray = fileName.split("/");
         fileName = new StringBuffer(fileNameArray[0]).reverse()
           .toString();
    Si j'ai bien compris, c'est juste pour récupérer la dernière partie de l'url...
    mais... quid des parametres ? de l'ancre ?
    Puisqu'on a une URL, autant l'utiliser:
    retourne le nom de fichier (dernière partie du path) correspondant à l'URL.
    Bien sur, il faut avoir un objet URL, mais ce devrait être le cas dès le onHandleIntent()

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    File folder = new File(BaseActivity.mDownloadDest);
    Là encore référence à BaseActivity, qui peut ne pas exister....mDownloadDest a null donc.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
    Utiliser simplement:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    } catch (Exception e) {
        Log.e("Downloader","Failure to download file",e);
    }
    D'ailleurs du coup, le code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    if (!folder.exists()) {
          success = folder.mkdir();
         }
         if (!success) {
    Ne sert plus à rien, il suffit de faire:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
       if (!folder.mkdir())
          throw new IOException("Couldn't create folder "+folder);
    Le WebNetworkAlert me semble bizarre aussi.... déclaré comme un type ("W"ebNetworkAlert) mais est une fonction.... qui fait un dialogue dont le bouton "ok" ne fait rien... bizarre bizarre..
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  7. #7
    Nouveau membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2013
    Messages
    37
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2013
    Messages : 37
    Points : 33
    Points
    33
    Par défaut
    J'ai un petit problème concernant la notification une fois j'ai téléchargé un fichier
    une erreur me parait

    E/AndroidRuntime(11560): android.app.RemoteServiceException: Bad notification Couldn't expand RemoteViews for: StatusBarNotification(package=com.example.cloud id=198990 tag=null notification=Notification(vibrate=null,sound=null,defaults=0x0,flags=0x0))
    E/AndroidRuntime(11560): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1048)
    Le code de la notification est le suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    public void notificationDownload() {
     
    		isDownload = false;
    		notificationManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
    		String MyText = "Downloading";
    		titleText = URLDecoder.decode(fileName);
    		notiText = "Downloading...";
     
    		Log.d("Download file name ",fileName + " <=======");
    		notification = new Notification(R.drawable.icon, MyText,
    				System.currentTimeMillis());
     
    		Intent MyIntent = new Intent(Intent.ACTION_VIEW);
     
    		MyIntent.putExtra("extendedTitle", titleText);
     
    		PendingIntent StartIntent = PendingIntent.getActivity(
    				getApplicationContext(), 0, MyIntent, 0);
    		notification.setLatestEventInfo(getApplicationContext(), titleText,
    				notiText, StartIntent);
     
    		notificationManager.notify(NOTFICATION_ID, notification);
     
    		Intent i = new Intent(getApplicationContext(), Downloader.class);
    		i.setData(Uri.parse(mFileUrl));
    		i.putExtra(Downloader.EXTRA_MESSENGER, new Messenger(notiHandler));
     
    		startService(i);
    	}
     
    	public static void updateNotation() {
    		progress++;
    		notification.contentView.setProgressBar(R.id.status_progress, 100,
    				progress, false);
     
    		// inform the progress bar of updates in progress
    		notificationManager.notify(NOTFICATION_ID, notification);
    	}
     
    	private Handler notiHandler = new Handler() {
    		@Override
    		public void handleMessage(Message msg) {
     
    			notificationManager.cancel(NOTFICATION_ID);
     
    			notificationManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
    			String myText = "Downloaded";
    			titleText = URLDecoder.decode(fileName);
    			notiText = "Downloaded";
    			notification = new Notification(R.drawable.icon, myText,
    					System.currentTimeMillis());
     
    			Intent myIntent = new Intent(Intent.ACTION_VIEW);
     
    			myIntent.putExtra("extendedTitle", titleText);
     
    			myIntent.setData(Uri.parse(mDownloadDest));
     
    			PendingIntent startIntent = PendingIntent.getActivity(
    					getApplicationContext(), 0, myIntent, 0);
    			notification.setLatestEventInfo(getApplicationContext(), titleText,
    					notiText, startIntent);
     
    			notificationManager.notify(NOTFICATION_ID, notification);
    			File file = new File(mDownloadDest,fileName);
    			fileName="";
     
    			openFile(file);
     
    			Log.i("DashBoard Download Done","FileName : "+fileName);
     
    		}
    	};

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Télécharger un fichier à partir d’un serveur distant
    Par BA_supFay dans le forum Développement Web en Java
    Réponses: 8
    Dernier message: 14/05/2015, 23h28
  2. Exécuter un logiciel à partir d’un serveur.
    Par Jehan57 dans le forum Hébergement
    Réponses: 4
    Dernier message: 08/07/2009, 14h15
  3. Exécuter un logiciel à partir d’un serveur.
    Par Jehan57 dans le forum Développement
    Réponses: 1
    Dernier message: 06/07/2009, 14h34
  4. Télecharger un fichier d'un serveur vers mon PC
    Par diamonds dans le forum Général Conception Web
    Réponses: 11
    Dernier message: 08/02/2007, 16h06
  5. lien vers un fichier à partir d’un bouton
    Par amelhog dans le forum Général JavaScript
    Réponses: 9
    Dernier message: 10/08/2005, 16h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo