美文网首页
Android 的 Service

Android 的 Service

作者: 图之 | 来源:发表于2019-01-18 14:13 被阅读0次

线程和服务的区别:

1.service默认运行在主线程中,执行耗时操作时,在线程中开启
2.service优先级高于后台挂起的Activity或者Thread,所以当系统资源不够时优先杀死Activity和Thread
3.Thread运行独立于Activity,当Activity被finish之后,如果没有主动停止Thread或者Thread里面的run方法未执行完,Thread也会一直执行,这时候当Activity被finish之后不再持有该线程,无法控制之前创建的线程,而Service可以

Service

Service:是Android 中实现程序后台运行的解决方案,适合去执行一些不需要和用户交互,而且要求长期运行的任务,不依赖于任何用户界面,即使程序被切换到后台,或打开其他应用程序,服务仍能保持正常的运行。当进程被杀掉,服务就停止了。
Service不能执行耗时的操作,如网络请求,拷贝数据库,大文件等
使用Android 的Service一定要在AndroidManifest清单文件中声明,是让PackageManagerService能解析出该Service, 并建立对应的数据结构。

Activity启动service

//获取服务的对象,如播放音乐
Intent intent = new Intent(context,Service.class);
startService(intent )
//和
//仅开启一个后台服务
bindService(intent )

Service的生命周期

startService()和bindService() 两种启动方式
startService():主要用于执行后台计算
bindService() :主要用于和其他组件的交互
这两种状态可以共存(一个service既可以处于启动状态,同时也可以处于绑定状态)
绑定模式和非绑定模式,两种模式的混合使用

绑定模式startService():

第一次调用:onCreate(),onStartCommand(),onStart(),当service 进行运行状态,再次调用startService(),就不会创建新的service对象。使用onStartCommand(),当Service关闭的时候调用onDestory()。无论启动了多少次service,只需调用一次stopService()即可杀掉service。
oncreate():该方法在整个生命周期中只会在创建service时调用一次;
onDestory():该方法只会当service被关闭时调用一次;
onStartCommand(intent ,flag,startId):当客户端调用startService(Intent)方法时会回调,可调用多次startService(),但不会在创建新的service对象,复用之前的,但会继续回调onStartService()

非绑定模式bindService() :

第一次调用:第一次bindService()时,onCreate(),onBind(),第二次:不会调用onBind(),而是直接把IBinder对象传递给其他后来增加的对象。解决绑定的时候调用onUnbind()e,onDestory()
调用onUnBind()时,若只有一个对象绑定了此服务,那么onUNBind()和onDestory()方法将会被嗲用,当多个对象绑定同一个Service的话。当一个对象完成互动后,调用onUnBindService来解除绑定,当所有对象都和service解绑后,系统会销毁Service

注意:Service实例只有一个,一个Service可以被绑定多次,只有所有对象都执行了onBind()方法后Service才会被销毁,若有一个对象执行了onStart(),这时候其他的都执行了unbind(),该Service也不会被销毁。

举个栗子:

public class GetService extends Service {
    SensorModel sensorModel;
    /**
     * 报警通知id
     */
    private int notificationID = 1;
    /**
     * 通知管理器
     */
    private NotificationManager notificationManager;
    private NotificationCompat.Builder builder;
    /**
     * 获取传感器列表服务开关
     */
    private boolean isPower = true;


//和activity绑定
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //设置通知渠道
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(String.valueOf(notificationID), "设备报警通知", NotificationManager.IMPORTANCE_HIGH);

            notificationChannel.enableLights(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        Intent intent = new Intent(this, AlarmListActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1000, intent, 0);
        //2.实例化通知栏构造器
        builder = new NotificationCompat.Builder(getApplicationContext(), String.valueOf(notificationID));
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(pendingIntent);
        //初始化model
      Model = newModel();
    
        Model.getList(1, null, iCallBackListener);
    }

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

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

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 扫描结果监听
     */
    ICallBackListener<Bean> iCallBackListener = new ICallBackListener<Bean>() {

        @Override
        public void onSuccess(Bean response) {

           Bean bean = JSON.parseObject(localSensorJson,Bean.class);
            if (bean != null) {

                outer:
                for (int i = 0; i < response.getData().getList().size(); i++) {
                   Entity data = response.getData().getList().get(i);

                    for (Entity entity : bean.getData().getList()) {

                        if (entity.getId() == data.getId()) {

                            if (entity.getStatus() != data.getStatus()) {
                                //发送广播
                                Intent intent = new Intent(Constant.broad_Change);
                                sendBroadcast(intent);

                                if (data.getStatus() != Enum.NORMAL.getValue()) {

                                    builder.setContentText(Name + data.getName() + data.getTypeForShow() + data.getStatusForShow() + "报警");
                                    notificationManager.notify(notificationID, builder.build());
                                    break outer;
                                }
                            }

                        }
                    }
                }
            }


            handler.sendEmptyMessageDelayed(0, 3000);


        }

        @Override
        public void onFailure(String message) {
            //睡眠5秒再次查询
            handler.sendEmptyMessageDelayed(0, 3000);
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            sensorModel.getList(1, null, iCallBackListener);
        }
    };



    public class GetListThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (isPower) {
                sensorModel.getList(1, null, iCallBackListener);
            }

        }
    }
}

相关文章

网友评论

      本文标题:Android 的 Service

      本文链接:https://www.haomeiwen.com/subject/jvnhrqtx.html