四大组件之一服务(service)

一.Android Service服务:

Android中的服务是运行在后台的服务,他是不可见的没有界面的东西。你可以启动一个服务Service来播放音乐,或者记录你地理信息位置的改变,或者启动一个服务来运行并一直监听某种动作。Service和其他组件一样,都是运行在主线程中,因此不能用它来做耗时的请求或者动作。你可以在服务中开一一个线程,在线程中做耗时动作。

这里写图片描述

代码实现会好理解

第一种 IntentService(Started Service)

  • 调用者和服务之间没有联系,即使调用者退出了,服务依然在进行

1、创建继承Service的类

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class ExampleService extends Service {

    private static final String TAG = "ExampleService";

    public ExampleService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "ExampleService===>>onCreate");
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        Log.i(TAG, "ExampleService===>>onStart");

        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.i(TAG, "ExampleService===>>onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy()
    {
        Log.i(TAG, "ExampleService===>>onDestroy");
        super.onDestroy();
    }


}

2、在一个Activity上设置启动和停止Button

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.chenxh.myttestapplication.R;
import com.example.chenxh.myttestapplication.service.ExampleService;

public class ServiceActivity extends AppCompatActivity implements Button.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        findViewById(R.id.startService).setOnClickListener(this);
        findViewById(R.id.stopService).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {


        switch (view.getId()) {
            case R.id.startService:
                Toast.makeText(this, "开启服务", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ServiceActivity.this, ExampleService.class);

                startService(intent);

                break;
            case R.id.stopService:
                Toast.makeText(this, "关闭服务", Toast.LENGTH_SHORT).show();
                Intent stopIntent = new Intent(ServiceActivity.this, ExampleService.class);

                stopService(stopIntent);

                break;
        }
    }


}

activity_serivice.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.chenxh.myttestapplication.activity.ServiceActivity">

    <Button
        android:id="@+id/startService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启服务"
        />
    <Button
        android:id="@+id/stopService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关闭服务"
        />
</LinearLayout>

LogCat日志:

//点击第一次启动
ExampleService===>>onCreate
ExampleService===>>onStartCommand
ExampleService===>>onStart
//点击第一次启动
ExampleService===>>onStartCommand
ExampleService===>>onStart
//点击第一次启动
ExampleService===>>onStartCommand
ExampleService===>>onStart
//点击停止服务
ExampleService===>>onDestroy

说明onCreate()只走一次 onStartCommand()与onstart()会再次执行 ,但是onstart()已经过时了,当停止服务会走onDestory()方法。

第二种:BindService中使用bindService()方法绑定服务,调用者和绑定者绑在一起,调用者一旦退出服务也就终止了

1.ExampleService.java

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class ExampleService extends Service {

    private static final String TAG = "BindService";

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Log.i(TAG, "BindService-->onBind()");
        return myBinder;
    }

    public class MyBinder extends Binder {

        public ExampleService getService(){
            Log.i(TAG, "BindService-->getService()");
            return ExampleService.this;
        }
    }
    private MyBinder myBinder = new MyBinder();
    public void MyMethod(){
        Log.i(TAG, "BindService-->MyMethod()");
    }
}

2.ServiceActivity.java

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ServiceActivity extends AppCompatActivity implements Button.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        findViewById(R.id.startService).setOnClickListener(this);
        findViewById(R.id.stopService).setOnClickListener(this);
        findViewById(R.id.bindService).setOnClickListener(this);
        findViewById(R.id.unbindService).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.startService:
                Toast.makeText(this, "开启服务", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ServiceActivity.this, ExampleService.class);

                startService(intent);

                break;
            case R.id.stopService:
                Toast.makeText(this, "关闭服务", Toast.LENGTH_SHORT).show();
                Intent stopIntent = new Intent(ServiceActivity.this, ExampleService.class);

                stopService(stopIntent);

                break;
            case R.id.bindService:
                bindService();
                break;
            case R.id.unbindService:
                unBind();
                break;


        }
    }

    private void bindService(){
        Intent intent = new Intent(this,ExampleService.class);
        bindService(intent,conn, Context.BIND_AUTO_CREATE);

    }
    private void unBind(){
        if(flag==true){
            unbindService(conn);
            Log.v("BindService","unBInd()");
            flag = false;
        }
    }

    private boolean flag;
    private ServiceConnection conn = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            ExampleService.MyBinder binder = (ExampleService.MyBinder) iBinder;
            ExampleService exampleService = binder.getService();
            exampleService.MyMethod();
            flag = true;

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };


}

实际LogCat日志结果:


//第一次点击绑定服务
I/BindService: BindService-->onBind()
I/BindService: BindService-->getService()
I/BindService: BindService-->MyMethod()
//第二次点击绑定
//第三次点击绑定
// 点击解绑
V/BindService: unBInd()

猜你喜欢

转载自blog.csdn.net/mr_chenxu/article/details/78895244