2012-02-07 17 views
6

En mi proyecto necesito crear un servicio en android. Soy capaz de registrar el servicio como este:Creando un servicio de fondo en Android

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" > 

    <service android:enabled="true" 
    android:name=".ServiceTemplate"/> 
     <activity 
     android:name=".SampleServiceActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 
     <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

Estoy llamando a este servicio dentro de una actividad, como a continuación: -

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Intent service = new Intent(getApplicationContext(), ServiceTemplate.class); 
    this.startService(service); 
} 

Pero si mato a la actividad actual, el servicio también es destruido. Necesito que este servicio siempre se ejecute en segundo plano. ¿Qué necesito hacer? ¿Cómo registro el servicio? ¿Cómo comienzo el servicio?

+1

puede usted por favor aceptar la respuesta que trabajó para esta pregunta? – abhinav

Respuesta

4

Pero si elimino la actividad actual, el servicio también está matando. Necesito que este servicio siempre se ejecute en segundo plano. ¿Lo que necesito hacer?

Si con "matar la actividad actual" quiere decir que está utilizando un asesino de tareas o Forzar detención desde la aplicación de configuración, su servicio se detendrá. No hay nada que puedas hacer al respecto. El usuario ha indicado que no quiere que su aplicación se ejecute más; por favor respete los deseos del usuario.

Si por "matar la actividad actual" quiere decir que presionó BACK o HOME o algo así, entonces el servicio debería seguir funcionando, al menos por un tiempo, a menos que llame al stopService(). No seguirá funcionando para siempre: Android acabará por deshacerse del servicio, porque demasiados desarrolladores escriben servicios que intentan "estar siempre en segundo plano". Y. por supuesto, el usuario puede matar el servicio cada vez que el usuario lo desee.

Un servicio solo debe estar "ejecutándose" cuando es entregando activamente valor al usuario. Esto generalmente significa que el servicio no debe estar "ejecutándose siempre en segundo plano". En su lugar, use AlarmManager y IntentService para trabajar de forma periódica.

+0

Estoy matando la actividad actual mediante el comando adb shell kill. Solo me gusta crear el servicio como alarma, notificación de SMS ... – Sathish

+0

@Sathish: no estoy al tanto de que el "comando adb shell kill" esté documentado, por lo que no sé cuáles son sus características. – CommonsWare

1

reemplazar este método:

public int onStartCommand(Intent intent, int flags, int startId) { 
    return Service.START_STICKY; 
} 
+0

¿Se ejecutará en segundo plano para siempre? –

3

intenta iniciar el servicio en hilo separado, de modo que cuando se destruirá su actividad el servicio no se verá afectado. Se ejecutará sin interrupción. Además, en el servicio, devuelva Service.START_STICKY de onStartCommand(intent, flags, startId) para asegurarse de que el servicio se vuelva a crear si el sistema lo elimina (Sistema operativo Android).

4

Aquí hay una forma semi-diferente de mantener el servicio en funcionamiento para siempre. Hay maneras de matar en el código si lo desea

servicio en segundo plano:

package com.ex.ample; 

import android.app.Service; 
import android.content.*; 
import android.os.*; 
import android.widget.Toast; 

public class BackgroundService extends Service { 

    public Context context = this; 
    public Handler handler = null; 
    public static Runnable runnable = null; 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show(); 

     handler = new Handler(); 
     runnable = new Runnable() { 
      public void run() { 
       Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show(); 
       handler.postDelayed(runnable, 10000); 
      } 
     }; 

     handler.postDelayed(runnable, 15000); 
    } 

    @Override 
    public void onDestroy() { 
     /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */ 
     //handler.removeCallbacks(runnable); 
     Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onStart(Intent intent, int startid) { 
     Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show(); 
    } 
} 

Así es como se inicia desde su actividad principal o dondequiera que usted desee:

startService(new Intent(this, BackgroundService.class)); 

onDestroy() se llamará cuando la aplicación se cierre o muera, pero el ejecutable simplemente lo inicia de nuevo. También debe eliminar las devoluciones de llamada del controlador.

Espero que esto ayude a alguien.

La razón por la que algunas personas hacen esto es debido a las aplicaciones corporativas, donde en algunos casos los usuarios/empleados no deben ser capaces de dejar ciertas cosas :)

http://i.imgur.com/1vCnYJW.png

4

puede crear servicio en segundo plano y llamar a que por AlarmManager

1- usted tiene que crear una clase BroadcastReceiver para llamar por AlarmManager

public class AlarmReceiver extends BroadcastReceiver 

{ 
    /** 

    * Triggered by the Alarm periodically (starts the service to run task) 

    * @param context 

    * @param intent 

    */ 

    @Override 

    public void onReceive(Context context, Intent intent) 

    { 

     Intent i = new Intent(context, AlmasService.class); 

     i.putExtra("foo", "AlarmReceiver"); 

     context.startService(i); 

    } 

} 

2-usted tiene que crear una clase IntentService para llamar por AlarmReceiver

public class AlmasService extends IntentService 

{ 

    public Context context=null; 

    // Must create a default constructor 
    public AlmasService() { 

     // Used to name the worker thread, important only for debugging. 
     super("test-service"); 

    } 

    @Override 

    public void onCreate() { 

     super.onCreate(); // if you override onCreate(), make sure to call super(). 

    } 


    @Override 
    protected void onHandleIntent(Intent intent) { 

     context=this; 
     try 

     { 

      Thread.sleep(5000); 

     } 

     catch (InterruptedException e) 

     { 

      e.printStackTrace(); 

     } 



     String val = intent.getStringExtra("foo"); 

     // Do the task here 
     Log.i("MyTestService", val); 

    } 

} 

3- hay que añadir AlarmReceiver como receptor y AlmasService como el servicio en el manifiesto

<service 
     android:name=".ServicesManagers.AlmasService" 
     android:exported="false"/> 

    <receiver 
     android:name=".ServicesManagers.AlmasAlarmReceiver" 
     android:process=":remote" > 
    </receiver> 

4-ahora se puede iniciar el servicio y llamar AlarmManager en MainActivity

public class MainActivity extends AppCompatActivity 
{ 
    public static final int REQUEST_CODE = (int) new Date().getTime(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     scheduleAlarm(); 
    } 

    public void scheduleAlarm() 
    { 
     // Construct an intent that will execute the AlarmReceiver 
     Intent intent = new Intent(getApplicationContext(), AlmasAlarmReceiver.class); 
     // Create a PendingIntent to be triggered when the alarm goes off 
     final PendingIntent pIntent = PendingIntent.getBroadcast(
       this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
     // Setup periodic alarm every every half hour from this point onwards 
     long firstMillis = System.currentTimeMillis(); // alarm is set right away 
     AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
     // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP 
     // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY 
     alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, (long) (1000 * 60), pIntent); 



    } 
} 
Cuestiones relacionadas