Problème démarrage application boot android

Résolu/Fermé
Joker_ Messages postés 173 Date d'inscription mardi 13 octobre 2009 Statut Membre Dernière intervention 20 janvier 2023 - 21 oct. 2018 à 23:59
Joker_ Messages postés 173 Date d'inscription mardi 13 octobre 2009 Statut Membre Dernière intervention 20 janvier 2023 - 26 oct. 2018 à 17:34
Bonsoir,

Mon projet consiste à réaliser une application qui connecte chaque 10 sec à un site web pour voir s'il y a des mise à jours même si l'application est fermée... j'ai réussit à créer un Service qui peut réaliser cette tache lorsque l'application fermé ou bien démarrée. Maintenant je veux améliorer mon application par démarrer automatiquement ce Service lors du démarrage Android, pour ce faire j'ai modifier mon fichier manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tunisapp.rawabimobile"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity" />
        <activity android:name=".ProfileActivity" />
        <activity android:name=".MessagesActivity" />
        <activity android:name=".MessageActivity" />
        <service android:name=".MyService" />
        <receiver android:name=".MonBroadcastreceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

Ensuite j'ai créé le BroadcastReceiver:
public class MonBroadcastreceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, "reboot", duration);
        toast.show();
        Intent monServiceIntent = new Intent(context, MyService.class);
        context.startService(monServiceIntent);
    }
}

Et enfin voilà le code de mon Service:
public class MyService extends Service {
    Timer timer;
    TimerTask timerTask;
    final Handler handler = new Handler();
    @Override
    public IBinder onBind(Intent intent) {
        return  null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        startTimer();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
    }
    public void startTimer() {
        timer = new Timer();
        initializeTimerTask();
        timer.schedule(timerTask, 5000, 10000);
    }

    public void stoptimertask(View v) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        StrictMode.ThreadPolicy threadPolicy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(threadPolicy);
                        HttpClient client = new DefaultHttpClient();
                        String url="http://rawabiserv.000webhostapp.com/mysql_query_test.php";
                        HttpPost httpPost = new HttpPost(url);
                        int code=-1;
                        try {
                            HttpResponse response = client.execute(httpPost);
                            StatusLine statusLine = response.getStatusLine();
                            code=statusLine.getStatusCode();
                        }//fin try
                        catch(Exception e){
                            int duration = Toast.LENGTH_SHORT;
                            Toast toast = Toast.makeText(getApplicationContext(), "Exception:"+e.toString(), duration);
                            toast.show();

                        }//fin catch
                        int duration = Toast.LENGTH_SHORT;
                        Toast toast = Toast.makeText(getApplicationContext(), "StatusLine:"+Integer.toString(code), duration);
                        toast.show();
                    }
                });
            }
        };
    }
}


Lorsque je démarre l'appareil, le Service réussit à démarrer: le Toast affiche le message "reboot" suivit par un message système indiquant que mon application est plantée

Est ce qu'il y a une erreur dans mon code SVP???
merci d'avance cher lecteur
A voir également:

2 réponses

BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 3 894
22 oct. 2018 à 08:23
Salut,
suivit par un message système
Il faut avoir le réflexe d'aller dans les logs...
0
Joker_ Messages postés 173 Date d'inscription mardi 13 octobre 2009 Statut Membre Dernière intervention 20 janvier 2023 1
22 oct. 2018 à 15:39
Vouliez-vous dire les logs de Android de l'appareil ou l'application s’exécute ?? Si oui comment on peut faire ça??
je ne peux pas exécuter mon application directement dans mon PC à l'aide de simulateur accause d'une raison matériel
0
BunoCS Messages postés 15475 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 23 avril 2024 3 894
23 oct. 2018 à 08:46
Dans Android Studio, tu as une fenêtre qui s'appelle Logcat, généralement localisée en bas de l'IDE
0
Joker_ Messages postés 173 Date d'inscription mardi 13 octobre 2009 Statut Membre Dernière intervention 20 janvier 2023 1
26 oct. 2018 à 17:34
Merci beaucoup BunoCS!!! Vous me sauvez tous le temps par vos réponses très courtes :p

Mon problème était qu'une exception lancée :java.lang.IllegalStateException

après un simple recherche j'ai trouvé la solution :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, MyService.class));
    } else {
        context.startService(new Intent(context, MyService.class));
    }


de plus il faut ajouter dans le Service:
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}
0