studio programacion java android service

java - programacion - android studio pdf 2018



El servicio Android debe ejecutarse siempre(nunca pausar o detener) (8)

"¿Es posible ejecutar este servicio siempre como cuando la aplicación pausa y cualquier otra cosa?"

Sí.

  1. En el método service onStartCommand, devuelve START_STICKY.

    public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; }

  2. Inicie el servicio en segundo plano utilizando startService (MyService) para que siempre permanezca activo independientemente del número de clientes enlazados.

    Intent intent = new Intent(this, PowerMeterService.class); startService(intent);

  3. Crea la carpeta

    public class MyBinder extends Binder { public MyService getService() { return MyService.this; } }

  4. Definir una conexión de servicio.

    private ServiceConnection m_serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { m_service = ((MyService.MyBinder)service).getService(); } public void onServiceDisconnected(ComponentName className) { m_service = null; } };

  5. Enlace al servicio utilizando bindService.

    Intent intent = new Intent(this, MyService.class); bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);

  6. Para su servicio, es posible que desee una notificación para iniciar la actividad adecuada una vez que se haya cerrado.

    private void addNotification() { // create the notification Notification.Builder m_notificationBuilder = new Notification.Builder(this) .setContentTitle(getText(R.string.service_name)) .setContentText(getResources().getText(R.string.service_status_monitor)) .setSmallIcon(R.drawable.notification_small_icon); // create the pending intent and add to the notification Intent intent = new Intent(this, MyService.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); m_notificationBuilder.setContentIntent(pendingIntent); // send the notification m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build()); }

  7. Necesita modificar el manifiesto para iniciar la actividad en el modo superior único.

    android:launchMode="singleTop"

  8. Tenga en cuenta que si el sistema necesita los recursos y su servicio no es muy activo, puede ser eliminado. Si esto no es aceptable, lleve el servicio al primer plano usando startForeground.

    startForeground(NOTIFICATION_ID, m_notificationBuilder.build());

Creé un servicio y quiero ejecutar este servicio siempre hasta que mi teléfono se reinicie o se cierre. El servicio debe ejecutarse en segundo plano.

Código de muestra del servicio creado y servicios de inicio:

Comience el servicio:

Intent service = new Intent(getApplicationContext(), MyService.class); getApplicationContext().startService(service);

El servicio:

public class MyService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO do something useful HFLAG = true; //smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000); return Service.START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { // TODO for communication return IBinder implementation return null; } }

Declaración de manifiesto:

<service android:name=".MyService" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > </service>

¿Es posible ejecutar este servicio siempre como cuando la aplicación hace una pausa y cualquier otra cosa? Después de un tiempo, mi aplicación se detiene y los servicios también se detienen o detienen. Entonces, ¿cómo puedo ejecutar este servicio en segundo plano y siempre?


Añadir esto en manifiesto

<service android:name=".YourServiceName" android:enabled="true" android:exported="false" />

Agrega una clase de servicio.

public class YourServiceName extends Service { @Override public void onCreate() { super.onCreate(); // Timer task makes your service will repeat after every 20 Sec. TimerTask doAsynchronousTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { // Add your code here. } }); } }; //Starts after 20 sec and will repeat on every 20 sec of time interval. timer.schedule(doAsynchronousTask, 20000,20000); // 20 sec timer (enter your own time) } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO do something useful return START_STICKY; } }



Para iniciar un servicio en su propio proceso, debe especificar lo siguiente en la declaración xml.

<service android:name="WordService" android:process=":my_process" android:icon="@drawable/icon" android:label="@string/service_name" > </service>

Aquí puedes encontrar un buen tutorial que fue realmente útil para mí

http://www.vogella.com/articles/AndroidServices/article.html

Espero que esto ayude


Puede implementar startForeground para el servicio e, incluso si muere, puede reiniciarlo utilizando START_STICKY en startCommand() . No estoy seguro, aunque esta es la implementación correcta.


Si ya tiene un servicio y desea que funcione todo el tiempo, debe agregar 2 cosas:

  1. en el servicio mismo:

    public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; }

  2. En el manifiesto:

    android:launchMode="singleTop"

No es necesario agregar enlace a menos que lo necesite en el servicio.



Ya supere este problema, y ​​mi código de muestra es el siguiente.

Agregue la siguiente línea en su actividad principal, aquí BackGroundClass es la clase de servicio. Puede crear esta clase en New -> JavaClass (en esta clase, agregue el proceso (tareas) en el que necesita ocurrir en el fondo). Para conveniencia, denotelos primero con tono de llamada de notificación como proceso en segundo plano.

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

En BackGroundClass, solo incluye mis codificaciones y es posible que veas el resultado.

import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.provider.Settings; import android.support.annotation.Nullable; import android.widget.Toast; public class BackgroundService extends Service { private MediaPlayer player; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI); player.setLooping(true); player.start(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); player.stop(); } }

Y en AndroidManifest.xml, intente agregar esto.

<service android:name=".BackgroundService"/>

Ejecute el programa, solo abra la aplicación, puede encontrar la alerta de notificación en el fondo. Incluso, puede salir de la aplicación pero aún así puede haber escuchado la alerta de tono de llamada a menos que y hasta que apague la aplicación o Desinstale la aplicación. Esto denota que la alerta de notificación está en el proceso de fondo. De esta manera, puedes agregar algún proceso para el fondo.

Atención: Por favor, no verifique con TOAST, ya que se ejecutará solo una vez aunque esté en proceso de fondo.

Espero que ayude ... !!