Android——service简单介绍


Service生命周期

life-cycle


Service启动流程

  • 以startService启动

1.首次启动时:onCreate -> onStartCommand
2.已经被以startService或者bindService方式启动过:-> onStartComand

  • 以bindService启动

1.首次启动时:onCreate -> onBind
2.已经被以startService方式启动过: onBind
3.已经被以bindService方式启动过: 不会回调任何生命周期方法


本地Sevice

//Service类
public class NormalService extends Service {
    private static final String TAG = "NormalService";
    private static Binder mMyBinder;
    public NormalService() {
        mMyBinder = new MyBinder();
    }

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


    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.d(TAG, "onRebind: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return mMyBinder;
    }

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

    public String decorateString(String str){
        return str + "normalService";
    }
}

//Activity中bingService
private NormalService normalService;
private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        NormalService.MyBinder myBinder = (NormalService.MyBinder) service;
        normalService = (NormalService) myBinder.getService();
        Toast.makeText(MainActivity.this,normalService.decorateString("hello"),Toast.LENGTH_LONG).show();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};
 Intent intent = new Intent(this,NormalService.class);
    bindService(intent,serviceConnection,BIND_AUTO_CREATE);

远程Service(不同进程)

//创建AIDL接口
// IMyAidlInterface.aidl
package com.example.servicedemo;

// Declare any non-default types here with import statements

interface IMyAidlInterface {
    String decorateString(String str);
}

//构建之后会看到生成的具体接口文件
//创建远程服务类:xml声明
<service
    android:name=".RemoteService"
    android:process="com.mt.sanqii.top.remote"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.mt.sanqi.test"/>
    </intent-filter>
</service>

//远程服务具体java类
public class RemoteService extends Service {
    private static RemoteBinder remoteBinder;
    public RemoteService() {
        remoteBinder = new RemoteBinder();
    }

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

    public class RemoteBinder extends IMyAidlInterface.Stub{

        @Override
        public String decorateString(String str) throws RemoteException {
            return RemoteService.this.decorateString(str);
        }
    }
    public String decorateString(String str) throws RemoteException {
        return str + "RemoteService";
    }

}

//Activity中使用bindService链接
private IMyAidlInterface iMyAidlInterface;
private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
        try {
            Toast.makeText(MainActivity.this,iMyAidlInterface.decorateString("hello"),Toast.LENGTH_LONG).show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};

//隐式启动
Intent intent = new Intent();
intent.setAction("com.mt.sanqi.test");
intent.setPackage("com.example.servicedemo");

//显示启动:推荐使用
//参数一:远程service的包名
//参数二:远程service的包名+类名
ComponentName componentName = new ComponentName("com.example.servicedemo",
                "com.example.servicedemo.RemoteService");
intent.setComponent(componentName);
bindService(intent,serviceConnection,BIND_AUTO_CREATE);


IntentService用法

将主要工作在子线程中进行,用startService多次启动时,这些任务将会按照启动时间进行排队执行。

//实现IntentService类
public class MyIntentService extends IntentService {

    private static final String TAG = "MyIntentService";

    private static final String ACTION_A = "com.example.servicedemo.action.A";
    private static final String ACTION_B = "com.example.servicedemo.action.B";

    private static final String EXTRA_PARAM = "com.example.servicedemo.extra.PARAM";

    public MyIntentService() {
        super("MyIntentService");
    }

    // 工作A
    public static void startActionWorkA(Context context, String param) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_A);
        intent.putExtra(EXTRA_PARAM, param);
        context.startService(intent);
    }

    // 工作B
    public static void startActionWorkB(Context context, String param) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_B);
        intent.putExtra(EXTRA_PARAM, param);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            String param = null;
            if (ACTION_A.equals(action)) {
                param = intent.getStringExtra(EXTRA_PARAM);
                handleActionA(param);
            } else if (ACTION_B.equals(action)) {
                param = intent.getStringExtra(EXTRA_PARAM);
                handleActionB(param);
            }
        }
    }

    private void handleActionA(String param) {
        Log.d(TAG, "handleActionA: " + param);
    }

    private void handleActionB(String param) {
        Log.d(TAG, "handleActionB: " + param);
    }
}

//Activity中选择提供的任务执行
MyIntentService.startActionWorkA(this,"hello");
MyIntentService.startActionWorkB(this,"hello");


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值