Análisis Android Servicio (ciclo de vida, el modo de puesta en marcha, el Servicio de recepción)

El servicio es uno de los cuatro componentes principales de Android, la segunda en importancia única actividad, documento Android lo describe de la siguiente manera:

componente de servicio representa una operación que consume tiempo sin afectar a los usuarios o funcionalidad de otras aplicaciones para su uso.

En androide todos los componentes se están ejecutando en el hilo principal, utilice el servicio cuando se necesita una operación que consume tiempo para abrir otro hilo. Pero el uso de servicio, operación que consume tiempo más manejable porque el servicio tiene un ciclo de vida diferente. Por ejemplo, las aplicaciones que juegan música, generalmente controlados por el servicio.

Servicio de inicio

El servicio puede iniciarse de dos maneras: Context.startService () o Context.bindService ();

Context.startService () método y la actividad de inicio similar a:


    Intent i = new Intent(ServiceActivity.this, ServiceA.class);
    startService(i);

Después de usar este método para iniciar el servicio, las llamadas de servicio era onStartCommand método () onCreate () y.
Servicio está parando método:


Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
stopService(i);

También puede llamar al () deja método de stopSelf Servicio.

Cuando el servicio se llamará la destrucción de su método onDestory (), donde la operación para liberar el recurso.

Tenga en cuenta que el lanzamiento múltiple de servicio, método onCreate () no se llama varias veces, sólo la primera vez las llamadas comienzan (o la destrucción del Servicio de re-arranque), pero el método onStartCommand () serán llamados varias veces.

La segunda manera: Context.bindService ()


Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
bindService(i,connection,BIND_AUTO_CREATE);

método Unbind:


Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
unbindService(connection);

Servicio iniciado de esta manera, cuando el enfoque del ciclo de vida de la siguiente manera:

bindService-> onCreate-> onBind-> unbindService-> onUnbind-> OnDestroy

Si usted no llama método unbindService, cuando la actividad de esta destrucción de servicio puede ser destruido, pero se produce la pérdida de memoria, se informará el error de la siguiente manera:


08-30 00:12:06.060 1937-1937/example.ylh.com E/ActivityThread: Activity example.ylh.com.service_demo.ServiceTestActivity has leaked ServiceConnection example.ylh.com.service_demo.ServiceTestActivity$1@513a0eb that was originally bound here
······                                                              

Por lo tanto, con el fin de evitar pérdidas de memoria, o que unbind honesto.

bindService inicio, tiene que pasar dos parámetros, el primero es la intención, el segundo es ServiceConnection, esto es lo que es?

Después del inicio sabíamos servicio, la frente El servicio comenzó a funcionar, pero ¿cómo e interactuar con él de actividad, esta vez en la necesidad ServiceConnection, ServiceConnection es una interfaz:


private ServiceConnection connection = new ServiceConnection() {
       @Override
       public void onServiceConnected(ComponentName name, IBinder service) {
           Log.e(TAG,"onServiceConnected");
       }

       @Override
       public void onServiceDisconnected(ComponentName name) {
           Log.e(TAG, "onServiceDisconnected");
       }
   };

onServiceConnected método se llama tan pronto después de servicio onBind, expresó la actividad de unión y el éxito del servicio, asociado.
manera de representar servicio y la actividad asociada con la insuficiencia onServiceDisconnected, que no esté obligado, en general, no se llama.
onServiceConnected método toma dos parámetros, el segundo parámetro es un IBinder, IBinder este método es el valor de retorno Servicio onBind, por lo que podemos onBind devolver el valor y la forma onServiceConnected para la actividad y del asociado de servicios, a continuación es un caso típico :

actividad de xml:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn1"
            android:text="start"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:text="stop"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn3"
            android:text="action"/>
    </LinearLayout>

</RelativeLayout>

Código de la actividad:


package example.ylh.com.service_demo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import example.ylh.com.R;

/**
 * Created by yanglihai on 2017/8/17.
 */

public class ServiceTestActivity extends Activity {

    public static final String TAG = ServiceTestActivity.class.getSimpleName();

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((ServiceA.MyBinder) service).getService();
            Log.e(TAG,"onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "onServiceDisconnected");
        }
    };

    private ServiceA mService ;

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

        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
                bindService(i,connection,BIND_AUTO_CREATE);
            }
        });

        findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ServiceTestActivity.this, ServiceA.class);
                unbindService(connection);
            }
        });

        findViewById(R.id.btn3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mService.doSomething();
            }
        });
    }
}

código de servicio:


package example.ylh.com.service_demo;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by yanglihai on 2017/8/17.
 */

public class ServiceA extends Service {

    static final String TAG = ServiceA.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "oncreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.e(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.e(TAG, "onDestroy");
    }

    @Override
    public boolean bindService(Intent service, ServiceConnection conn, int flags) {

        Log.e(TAG, "bindService");
        return super.bindService(service, conn, flags);
    }

    @Override
    public void unbindService(ServiceConnection conn) {
        super.unbindService(conn);
        Log.e(TAG, "unBindService");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind" );
        return mbinder;
    }


    public void doSomething(){
        Log.e(TAG, "doSomething");
    }

    private MyBinder mbinder = new MyBinder();

    public class MyBinder extends Binder{

        public ServiceA getService(){
            return ServiceA.this;
        }
    }

}

En el método onServiceConnected, mediante un giro fuerte para conseguir el aglutinante, en la instancia de servicio para obtener a través getService (), que puede ser manipulado desea.

Servicio de recepción
cuando se inicia el servicio, si no nos detenemos método de llamada, el servicio se ejecuta en segundo plano, pero cuando la memoria del sistema insuficiente puede matar a nuestro servicio, con el fin de evitar ser asesinada por el sistema, el servicio puede establecer el primer plano servicio, realizado por Service.startForeground llamada ().
En primer lugar en el código:

package example.ylh.com.service_demo;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import example.ylh.com.R;

/**
 * Created by yanglihai on 2017/8/17.
 */

public class ServiceA extends Service {

    static final String TAG = ServiceA.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "oncreate");

        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.btn_home_vedio);
        builder.setContentTitle("视频通知");
        builder.setContentText("someone send you a video");
        Notification notification = builder.build();
        startForeground(2,notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.e(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.e(TAG, "onDestroy");
    }

}

En onCreate, crear un aviso que le dice al usuario que hay una operación en segundo plano en ejecución. El primer parámetro startForeground () es un tipo int ID, las necesidades de identificación de observarse que esto no puede ser 0, o no puede crear la recepción.
Servicio durante esta operación, habrá una notificación de la barra de notificación hasta que se detuvo el servicio o llame al StopForeground (verdadero), una notificación será capaz de desaparecer.

Añadir que no importa qué tipo de modo de puesta en marcha, la necesidad de servicio a ser declarada en el archivo de manifiesto:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.ylh.com" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

        <service android:name=".service_demo.ServiceA" />

    </application>

</manifest>
Publicado 17 artículos originales · ganado elogios 12 · Vistas a 10000 +

Supongo que te gusta

Origin blog.csdn.net/qq_24295537/article/details/77692618
Recomendado
Clasificación