Android开发笔记

Android service 的使用

2019-03-25  本文已影响0人  天敦敦
  https://github.com/ww7hcom/Android-common 

创建service基类

package com.ww7h.ww.common.bases.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;


/**
 * Created by: Android Studio.
 * PackageName: com.ww7h.ww.common.bases.service
 * DateTime: 2019/3/25 15:24
 * @author ww
 */
public abstract class BaseService<T extends Service> extends Service implements ServiceInterface, ServiceConnection{

    protected ServiceBinder mBinder = new ServiceBinder();
    protected Context mContext;
    protected ConnectionCallBack mConnectionCallBack;

    /**
     * 获取当前页面的service的实例
     * @return 获取当前service的实例
     */
    protected abstract T getThisService();

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

    @Override
    public void bindService(Context context, Intent intent, ConnectionCallBack connection ,int flag) {
        mContext = context;
        intent.setClass(context, this.getClass());
        context.bindService(intent, this, flag);
    }

    @Override
    public void unbindService(ServiceConnection connection) {
        if (mContext != null) {
            mContext.unbindService(connection);
        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (mConnectionCallBack != null) {
            mConnectionCallBack.onServiceConnected(name,(ServiceBinder) service);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        if (mConnectionCallBack != null) {
            mConnectionCallBack.onServiceDisconnected(name);
        }
    }

    @Override
    public void onBindingDied(ComponentName name) {

    }

    @Override
    public void onNullBinding(ComponentName name) {

    }

    public class ServiceBinder extends Binder {
        /**
         * 获取当前service
         * @return 返回service实例
         */
        public  T getService() {
            return getThisService();
        }
    }
}

创建操作接口

package com.ww7h.ww.common.bases.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

/**
 * Created by: Android Studio.
 * PackageName: com.ww7h.ww.common.bases.service
 * User: ww
 * DateTime: 2019/3/25 16:32
 */
public interface ServiceInterface {

    /**
     * 绑定service
     * @param context 当前界面service
     * @param intent 绑定携带的参数
     * @param connection 连接回调
     * @param flag 连接标识
     */
    void bindService(Context context, Intent intent, ConnectionCallBack connection , int flag);

    /**
     * 接触service绑定
     * @param connection 链接
     */
    void unbindService(ConnectionCallBack connection);

    /**
     * 开始
     */
    void startDO();

    /**
     * 停止
     */
    void stopDO();

    interface ConnectionCallBack {

        /**
         * service连接成功
         * @param name ComponentName
         * @param service BaseService.ServiceBinder
         */
        <T extends Service> void onServiceConnected(ComponentName name, BaseService<T>.ServiceBinder service);

        /**
         * service连接断开
         * @param name ComponentName
         */
        void onServiceDisconnected(ComponentName name);

    }

}

定义具体service

package com.ww7h.androidutil.main.service;

import android.content.Intent;
import android.util.Log;
import com.ww7h.ww.common.apis.http.okhttp.HttpOkHttp;
import com.ww7h.ww.common.bases.service.BaseService;

/**
 * Created by: Android Studio.
 * Project Nam: AndroidUtil
 * PackageName: com.ww7h.androidutil.main.service
 * DateTime: 2019/3/25 18:39
 *
 * @author ww
 */
public class MainService extends BaseService<MainService> {
    @Override
    protected MainService getThisService() {
        return this;
    }

    @Override
    public void unbindService(ConnectionCallBack connection) {

    }

    @Override
    public void startDO() {
        HttpOkHttp.getInstance().requestGet("https://www.baidu.com", new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(String s) {
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction("com.ww7h.main_request");
                intent.putExtra("result", s);
                mContext.sendBroadcast(intent);
            }

            @Override
            public void requestFailure(String message) {
                Log.e("ww7h", "requestFailure" + message );
            }
        }, String.class);
    }

    @Override
    public void stopDO() {
    }
}

调用,配合使用BroadcastReceiver更新UI

package com.ww7h.androidutil.main

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import com.ww7h.androidutil.R
import com.ww7h.androidutil.main.adapter.MainAdapter
import com.ww7h.androidutil.main.model.MainModel
import com.ww7h.androidutil.main.service.MainService
import com.ww7h.androidutil.sign.AppSignActivity
import com.ww7h.ww.common.bases.activity.BaseActivity
import com.ww7h.ww.common.bases.broadcast.BroadcastReceiverInterface
import com.ww7h.ww.common.bases.broadcast.CommonBroadcastReceiver
import com.ww7h.ww.common.bases.service.BaseService
import com.ww7h.ww.common.bases.service.ServiceInterface
import com.ww7h.ww.common.bases.view.recyclerview.decoration.SpaceItemDecoration
import com.ww7h.ww.common.listeners.OnRecyclerItemClick
import com.ww7h.ww.common.utils.DensityUtil
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity<MainActivity>() , OnRecyclerItemClick<MainModel>,
     ServiceInterface.ConnectionCallBack, BroadcastReceiverInterface.BroadcastReceiverCallBack {


    private lateinit var adapter : MainAdapter
    private lateinit var clickModel : MainModel
    private lateinit var serviceInterface:ServiceInterface
    private lateinit var broadcastReceiverInterface: BroadcastReceiverInterface

    override val contentView: Int
        get() = R.layout.activity_main

    override fun initAction() {

    }

    override fun initView() {
        title = "⚙️工具大全"
        adapter = MainAdapter(this, this)
        app_util_rv.layoutManager = LinearLayoutManager(this)
        app_util_rv.adapter = adapter
        app_util_rv.addItemDecoration( SpaceItemDecoration(DensityUtil.dp2px(this,1f),1))

        val mainArray = object : java.util.ArrayList<MainModel>(){
            init {
                add(MainModel("应用信息", AppSignActivity::class.java))
            }
        }
        adapter.addDataList(mainArray)

        broadcastReceiverInterface = CommonBroadcastReceiver()
        broadcastReceiverInterface.register(this, "com.ww7h.main_request", this)

        serviceInterface = MainService()
        val intent = Intent()
        serviceInterface.bindService(this, intent, this, 0x1001)
    }

    override fun onItemClick(t: MainModel?) {
        clickModel = t!!
        serviceInterface.startDO()
    }

    override fun onDestroy() {
        serviceInterface.unbindService(this)
        super.onDestroy()
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        serviceInterface.stopDO()
    }

    override fun onServiceConnected(name: ComponentName?, service: BaseService<*>.ServiceBinder?) {

    }

    override fun receiverCallBack(context: Context?, intent: Intent?) {
        Log.e("ww7h", intent?.getStringExtra("result"))
        val intent = Intent()
        intent.setClass(applicationContext, clickModel.activityClass!!)
        intent.putExtra("title", clickModel.utilName)
        startActivity(intent)
    }

}
上一篇下一篇

猜你喜欢

热点阅读