本地服务(local Service)的实现
阅读原文时间:2021年04月20日阅读:1

定义;
--后台运行、不可见、没有界面
--优先级高于Activity
用途:
--播放音乐、记录地理信息位置的改变、监听某种动作
注意:
--运行在主线程,不能用来做耗时的请求活动
--可以在服务中开一个线程,在线程中做耗时动作
类型:
1、本地服务(local Service)
------应用程序内部
启动方式:
-------StartService ----StopService()----stopService()-----stopSelf()------stopSelfResult()
-------BindService ----先要unbindService然后停掉(启动源销毁时一定要先解绑定)
2、远程服务(Remote Service)
------Android系统内部的应用程序之间
------定义IBinder接口
生命周期:
-------StartService:---->startService()--->onCreate()--->onStartCommmand()--->ServiceRunning(调用停止方法)--->onDestroy()--->Service down
-------BindService: ---->bindService()--->onCreate()--->onBind()--->Service绑定了(调用解绑定)--->onUnbind()--->onDestroy()--->Service down
注:开启Service没有关闭以前onCreate()只调用一次,第二次直接开启onStartCommmand()方法
Start方式特点:
---服务跟启动源没有任何联系
---无法得到服务对象
Bind方式特点:
---通过Ibinder接口实例,返回一个ServiceConnection对象给启动源
---通过ServiceConnection对象的相关方法可以得到Service对象

本地服务Start启动:直接用intent(context,class)——>startService(mintent)
补充:intent是四大组件关联的纽带
本地服务Bind启动:
intent2 = new Intent(MainActivity.this, MyBindService.class);
bindService(intent2, conn, Service.BIND_AUTO_CREATE);
----参1、intent对象
----参2、ServiceConnection
----参3、让服务创建用的 用参数:Service.BIND_AUTO_CREATE让服务正常创建
得到Service的回传数据:
1、binder接口:
---重写一个类继承Binder类
---写一个返回当前的服务对象的方法;
2、实现绑定:
----实现一个ServiceConnection类
----重写了两个方法用来:链接、杀死服务

补充:有一个IntentService类,

1、它里面包含了线程可以处理耗时操作

2、不能并发执行,一个执行完了才能执行宁一个;
!!!!!!!!!!!注意啊!!!!!!要在清单文件中注册(我经常忘记!!!!!!)

我们先来看清单文件信息:

 <service android:name="zxx.serivce.StartService"></service>
        <service android:name="zxx.serivce.BindService"></service>

再看activity的实现:

package zxx.serivce;

import android.app.Activity;
import android.app.Service;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import zxx.serivce.BindService.MyBinderService;

public class MainActivity extends Activity {
    BindService service;
    ServiceConnection conn;
    Intent mintent2;
    Intent mintent;

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

        conn = new ServiceConnection() {
            /**
             * service和启动源接源出意外调用解除绑定不会
             */
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i("******","绑定意外崩溃了");
            }

            /**
             * service和启动源接源连接时调用。
             */
            @Override
            public void onServiceConnected(ComponentName name, IBinder ibinder) {

                service = ((MyBinderService) ibinder).getBindService();// 要把IBinder对象装换成我们自定义的类
            }
        };
    }
    public void doClick(View v) {
        switch (v.getId()) {
        case R.id.startService:
            mintent = new Intent(this, StartService.class);
            this.startService(mintent);
            // Toast.makeText(this, "点击了", 0).show();
            break;
        case R.id.BindService:
            mintent2 = new Intent(this, BindService.class);
            bindService(mintent2, conn, Service.BIND_AUTO_CREATE);
            break;
        case R.id.paly:
            service.paly();

            break;
        case R.id.unbinder:
            unbindService(conn);
            break;
        case R.id.stop:
            stopService(mintent);

            break;
        default:
            break;
        }
    }

    @Override
    protected void onDestroy() {
        stopService(mintent2);
        unbindService(conn);// 和启动源解绑
        super.onDestroy();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Service中的实现:

package zxx.serivce;

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

public class BindService extends Service {


    public class MyBinderService extends Binder {
        public BindService getBindService() {
            return BindService.this;
        }
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.i("****", ""+"BindService____onCreate()");
    }

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

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.i("****", ""+"BindService____onDestroy()");
    }
    public void paly(){
        Log.i("", "音乐播放了");
    }

}

StartService启动模式的实现:

package zxx.serivce;

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

public class StartService extends Service{

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.i("****", ""+"onCreate()");
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.i("****", ""+"onDestroy()");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i("****", ""+"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.i("****", ""+"onStart");
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="zxx.serivce.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Service启动方式:" />

    <Button
        android:id="@+id/startService"
        android:layout_width="288dp"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="startService" />

    <Button
        android:id="@+id/BindService"
        android:layout_width="290dp"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="BindService" />

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="曹卓" />

    <Button
        android:id="@+id/paly"
        android:layout_width="288dp"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="paly" />

    <Button
        android:id="@+id/unbinder"
        android:layout_width="287dp"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="unbinder" />

    <Button
        android:id="@+id/stop"
        android:layout_width="290dp"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="stop" />

</LinearLayout>