web-dev-qa-db-fra.com

exécuter le service même si l'application est fermée (supprimée)

Je veux que ce service fonctionne même si l'application est fermée (kiiled) ou même si l'utilisateur ne démarre pas l'application. Je veux que le service démarre après l'installation de l'application et à partir de ce moment, le service devrait toujours fonctionner.

public class notifications extends Service {

        @Override
        public IBinder onBind(Intent intent) {
                // TODO Auto-generated method stub
                return null;
        }

        @Override
    public void onCreate() {
    }

    @Override
    public void onStart(Intent intent, int startId) {
                final Handler handler = new Handler();
                final Runnable runb = new Runnable()
                {
                    public void run()
                    {
                        Toast.makeText(getApplicationContext(), " Service Started", Toast.LENGTH_LONG).show();
                        handler.postDelayed(this, 10000);
                    }
                };
                handler.postDelayed(runb, 0);

    }
    @Override
    public void onDestroy() {

    }
}*/

public class notifications extends IntentService
{
        private Timer mBackGroundTimer;
        public notifications()
    {
        super("myservice");
        this.mBackGroundTimer=new Timer();
    }
        @Override
        protected void onHandleIntent(Intent intent)
    {
        // TODO Auto-generated method stub
        mBackGroundTimer.schedule(new TimerTask()
        {
            public void run()
            {
                try
                {
                        Notification("This is message from Dipak Keshariya (Android Application Developer)", "This is Android Notification Message");
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        },1000, 2000);
    } // END onHandleIntent()
        private void mStopTimer()
    {
        //Call this whenever you need to stop the service
        mBackGroundTimer.cancel();
    }

        private void Notification(String notificationTitle, String notificationMessage) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            Android.app.Notification notification = new Android.app.Notification(R.drawable.ic_launcher, "A New Message from Dipak Keshariya (Android Developer)!",
            System.currentTimeMillis());

            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
            notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingIntent);
            notificationManager.notify(10001, notification);
        }
}

comment je peux faire ça?

15
tornal vergaro

En regardant votre code, il semble que vous souhaitiez que votre service envoie régulièrement des notifications.

En ce qui concerne son exécution continue, gardez à l'esprit que par sa conception, le système Android peut interrompre votre processus de service à tout moment. Vous pouvez influencer un peu cela, mais vous ne pouvez pas empêcher le système de tuer votre service.

Donc, pour vos actions périodiques, il serait préférable d'utiliser AlarmManager avec une alarme récurrente. Votre service serait alors essentiellement ponctuel, c'est-à-dire que vous effectuez l'action une fois, puis quittez.

Pour un peu de code, regardez ici par exemple:

Android: Gestionnaire d'alarmes

10
bgse

Vous devez implémenter la méthode OnStartCommand de la classe Service et y retourner Service.START_STICKY. Cela fera l'affaire. Si vous supprimez l'application, le service continuera de s'exécuter en arrière-plan. Cependant, si vous redémarrez votre téléphone, je pense que vous devez implémenter quelque chose d'autre dans votre application, ainsi qu'un service de démarrage ou quelque chose comme ça.

5
Hampel Előd

Je pense que la réponse à cette question est la suivante: https://developer.Android.com/training/sync-adapters/creating-sync-adapter.html

Adaptateurs de synchronisation introduits dans Google I/O 2013.

1
Kailas

Comme vous l'exigence est d'exécuter le service en arrière-plan. vous êtes sur la bonne voie pour utiliser le service, car il est uniquement destiné à un fonctionnement en arrière-plan.

depuis l'activité, vous pouvez démarrer le service en

startService(new Intent(activityName.this, serviceName.class));

ou si votre application n'a aucune activité, vous pouvez définir le service par défaut et le lanceur principal de l'application en mettant

<service Android:name="name of the service" >
 <intent-filter>
                <action Android:name="Android.intent.action.MAIN" />

                <category Android:name="Android.intent.category.LAUNCHER" />
            </intent-filter>
 </service>
1
Dinesh Prajapati