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

Android Discussion :

Service, redémarrage et plantage


Sujet :

Android

  1. #1
    Membre averti

    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2014
    Messages
    153
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Janvier 2014
    Messages : 153
    Points : 316
    Points
    316
    Par défaut Service, redémarrage et plantage
    Bonjour,

    Pour mon application, je créé un service qui va chercher des infos sur un serveur.
    En test, celui-ci redémarre de façon intenpestive.
    Voici l'image de mon téléphone:
    Nom : screenshot.png
Affichages : 89
Taille : 296,3 Ko

    Et voici le code du service:

    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
    174
    175
    176
    177
    178
    179
    180
    181
    import android.annotation.TargetApi;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.app.TaskStackBuilder;
    import android.content.Context;
    import android.graphics.Color;
    import android.os.Build;
    import android.os.IBinder;
    import android.content.Intent;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.Timer;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import java.io.OutputStreamWriter;
    import java.io.BufferedReader;
    import java.lang.reflect.Array;
     
    public class Majnotif extends Service {
     
     
        int n = -1;
        int compteur = 0;
     
        OutputStreamWriter writer = null;
        BufferedReader reader = null;
        HttpURLConnection connexion;
        String ligne = null;
        Array primaire = null;
     
            /**
             * Creates an IntentService.  Invoked by your subclass's constructor.
             *
             * @param name Used to name the worker thread, important only for debugging.
             */
        private final static String name = "compteur";
     
     
        @Override
        public void onCreate() {
     
            while (n < 0) {
                try {
                    Thread.sleep(20000);
                    createNotification();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
     
     
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
           // this.binder = null;
            //this.timer.cancel();
        }
     
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        public final void createNotification(){
     
     
     
     
            try {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
     
                if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
     
     
     
                    try {
     
                        String cookies = android.webkit.CookieManager.getInstance().getCookie("http://2oclick.com/");
     
     
                        Log.d("NetworkState", "Le cookie est : " + cookies);
                        // Encodage des paramètres de la requête
                        if (cookies != null) {
     
                            String donnees = "?" + URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode("valeur1", "UTF-8");
                            //donnees += "&" + URLEncoder.encode("identifiant2", "UTF-8") + "=" + URLEncoder.encode("valeur2", "UTF-8");
     
                            // On a envoyé les données à une adresse distante
                            URL url = new URL("http://2oclick.com" + donnees);
                            connexion = (HttpURLConnection) url.openConnection();
                            connexion.setDoOutput(true);
                            connexion.setChunkedStreamingMode(0);
     
                            /* On envoie la requête ici
                            writer = new OutputStreamWriter(connexion.getOutputStream());
     
                            // On insère les données dans notre flux
                            writer.write(donnees);
     
                            // Et on s'assure que le flux est vidé
                            writer.flush();
                            */
                            // On lit la réponse ici
                            reader = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
     
     
                            // Tant que « ligne » n'est pas null, c'est que le flux n'a pas terminé d'envoyer des informations
                            while ((ligne = reader.readLine()) != null) {
     
                                Log.d("resultat", ligne);
     
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                            /*try {
                                writer.close();
                            } catch (Exception e) {
                            }*/
                        try {
                            reader.close();
                        } catch (Exception e) {
                        }
                        try {
                            connexion.disconnect();
                        } catch (Exception e) {
                        }
     
                    }
     
                    if (ligne != null) {
     
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
                        mBuilder.setSmallIcon(R.drawable.notification);
                        mBuilder.setContentTitle("Titre de la notification");
                        mBuilder.setContentText("Texte de la notification");
                        mBuilder.setAutoCancel(true);
                        mBuilder.setVibrate(new long[]{1000, 1000});
                        mBuilder.setLights(Color.WHITE, 1000, 1000);
    // Creates an explicit intent for an Activity in your app
                        Intent resultIntent = new Intent(this, MainActivity.class);
     
    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
                        stackBuilder.addParentStack(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
                        stackBuilder.addNextIntent(resultIntent);
     
                        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                                compteur,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );
                        mBuilder.setContentIntent(resultPendingIntent);
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        //mNotificationManager.setAutoCancel();
    // mId allows you to update the notification later on.
                        //mNotificationManager.ledARGB = color.RED;
                        mNotificationManager.notify(compteur, mBuilder.build());
                        compteur++;
                    }
                }
     
            }
             catch (Exception e) {
                 e.printStackTrace();
            }
        }
     
    }
    Ma plateforme de formations digitales (développement Web, cybersécurité, SEO, Marketing digital)

    https://monformateurindependant.com

  2. #2
    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
    Je vois plusieurs choses:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    Thread.sleep(20000);
    createNotification();
    Outre le fait que Thread.sleep() ne devrait *jamais* être appelé, mais vraiment jamais... dans le genre même dans un scheduler de tâche on ne fait pas de "sleep" mais du object.wait(xxxxx) histoire de sortir plus tôt si besoin.
    Là on est carrément dans le thread principal de l'application, du coup, ça va le freezer => application suspendue par le système car non-responsive.

    En plus createNotification() fait des appels réseaux => NetworkOnMainThreadException
    (et de toute manière mauvaise idiée, puisqu'on est dans le thread principal)


    Petit rappel: "Service" dans Android n'est pas un thread à part, juste une "Activité" sans UI parallèle à celle(s) affichée(s) (permettant ainsi de partager des trucs entre plusieurs activité si besoin).
    IntentService rajoute une notion de thread pour "servir" l'Intent, mais Service tout court non => onCreate doit être super rapide.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  3. #3
    Membre averti

    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2014
    Messages
    153
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Janvier 2014
    Messages : 153
    Points : 316
    Points
    316
    Par défaut
    Bonjour

    J'ai utiliser wait() et supprimer la vérification réseau mais celà ne fonctionne pas encore, le service redémarre toujours...

    Voici le code corrigé

    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
     int n = -1;
        int compteur = 0;
     
        OutputStreamWriter writer = null;
        BufferedReader reader = null;
        HttpURLConnection connexion;
        String ligne = null;
        Array primaire = null;
        private Object lock = new Object();
     
            /**
             * Creates an IntentService.  Invoked by your subclass's constructor.
             *
             * @param name Used to name the worker thread, important only for debugging.
             */
        private final static String name = "compteur";
     
     
        @Override
        public void onCreate() {
     
            while (n < 0) {
                try {
                    synchronized (lock) {
                        lock.wait(20000);
                    }
                    createNotification();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
     
     
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
           // this.binder = null;
            //this.timer.cancel();
        }
     
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        public final void createNotification(){
     
     
                    try {
     
                        String cookies = android.webkit.CookieManager.getInstance().getCookie("http://listen.2oclick.com/");
     
     
                        Log.d("NetworkState", "Le cookie est : " + cookies);
                        // Encodage des paramètres de la requête
                        if (cookies != null) {
     
                            String donnees = "?" + URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode("valeur1", "UTF-8");
                            //donnees += "&" + URLEncoder.encode("identifiant2", "UTF-8") + "=" + URLEncoder.encode("valeur2", "UTF-8");
     
                            // On a envoyé les données à une adresse distante
                            URL url = new URL("http://listen.2oclick.com/notif.php" + donnees);
                            connexion = (HttpURLConnection) url.openConnection();
                            connexion.setDoOutput(true);
                            connexion.setChunkedStreamingMode(0);
     
                            /* On envoie la requête ici
                            writer = new OutputStreamWriter(connexion.getOutputStream());
     
                            // On insère les données dans notre flux
                            writer.write(donnees);
     
                            // Et on s'assure que le flux est vidé
                            writer.flush();
                            */
                            // On lit la réponse ici
                            reader = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
     
     
                            // Tant que « ligne » n'est pas null, c'est que le flux n'a pas terminé d'envoyer des informations
                            while ((ligne = reader.readLine()) != null) {
     
                                Log.d("resultat", ligne);
     
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                            /*try {
                                writer.close();
                            } catch (Exception e) {
                            }*/
                        try {
                            reader.close();
                        } catch (Exception e) {
                        }
                        try {
                            connexion.disconnect();
                        } catch (Exception e) {
                        }
     
                    }
     
                    if (ligne != null) {
     
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
                        mBuilder.setSmallIcon(R.drawable.notification);
                        mBuilder.setContentTitle("Titre de la notification");
                        mBuilder.setContentText("Texte de la notification");
                        mBuilder.setAutoCancel(true);
                        mBuilder.setVibrate(new long[]{1000, 1000});
                        mBuilder.setLights(Color.WHITE, 1000, 1000);
    // Creates an explicit intent for an Activity in your app
                        Intent resultIntent = new Intent(this, MainActivity.class);
     
    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
                        stackBuilder.addParentStack(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
                        stackBuilder.addNextIntent(resultIntent);
     
                        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                                compteur,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );
                        mBuilder.setContentIntent(resultPendingIntent);
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        //mNotificationManager.setAutoCancel();
    // mId allows you to update the notification later on.
                        //mNotificationManager.ledARGB = color.RED;
                        mNotificationManager.notify(compteur, mBuilder.build());
                        compteur++;
                    }
                }
    Merci d'avance
    Ma plateforme de formations digitales (développement Web, cybersécurité, SEO, Marketing digital)

    https://monformateurindependant.com

  4. #4
    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
    Heu... y a toujours les appels réseaux hein !

    URL => getConnection => ... appel réseau


    Et ma remarque sur le sleep() était que je ne vois pas l'interêt de faire un sleep.... passer à un "object.wait()" ne change rien... juste que c'est la bonne manière de faire quand on a *besoin* d'un sleep, hors on n'a quasiment jamais besoin d'un sleep.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  5. #5
    Membre averti

    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2014
    Messages
    153
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Janvier 2014
    Messages : 153
    Points : 316
    Points
    316
    Par défaut
    Ah, la oui,
    Mais c'est le but de l'application : aller chercher des données sur un serveur pour creer une notif. Je ne vois pas comment faire autrement...

    Merci
    Ma plateforme de formations digitales (développement Web, cybersécurité, SEO, Marketing digital)

    https://monformateurindependant.com

  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
    N'ayant pas la moindre idée de comment l'application fonctionne, difficile d'aider....

    Mais quelques pistes:

    1. Utiliser un IntentService. Cette classe permet déjà de gérer l'Intent dans un "thread" à part
    avantage => pas de gestion des thread à faire.
    inconvénient => obligation de passer par des intents pour communiquer avec le service

    2. Utiliser un Service (mais qui répond à quoi ? à qui ?). Si le service (onCreate ?) nécessite d'effectuer des opérations longues (database, fichiers, URL fetch, ...), utiliser une AsyncTask (ou au pire un Thread) pour encapsuler ces opérations.
    avantage => possibilité de gérer une interface de bind avancée.
    inconvénient => complexité pour l'implémentation.
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  7. #7
    Membre averti

    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2014
    Messages
    153
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Janvier 2014
    Messages : 153
    Points : 316
    Points
    316
    Par défaut
    Bonjour,

    J'ai utilisé un nouveau thread et cela fonctionne correctement,

    Il n'y a plus de plantage
    Merci de l'aide
    Ma plateforme de formations digitales (développement Web, cybersécurité, SEO, Marketing digital)

    https://monformateurindependant.com

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

Discussions similaires

  1. [Tomcat] plantage du service...
    Par nikalkal dans le forum Tomcat et TomEE
    Réponses: 6
    Dernier message: 08/06/2006, 12h10
  2. Réponses: 17
    Dernier message: 06/01/2006, 13h14
  3. Plantage de service sous Windows 2003 server
    Par akasim73 dans le forum MFC
    Réponses: 2
    Dernier message: 10/11/2005, 15h49
  4. [TOMCAT 5.0.30] Redémarrage du service obligatoire !
    Par Enfa dans le forum Tomcat et TomEE
    Réponses: 2
    Dernier message: 13/09/2005, 11h51
  5. [CVS]: plantage du service sous win32
    Par sleepy2002 dans le forum Eclipse Java
    Réponses: 2
    Dernier message: 01/06/2004, 10h09

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