Android startService和bindService混合使用、以及前台服务;

Service简单来说就是一个看不见的Activity,在后台默默运行;

可以混合开启Service,无论先startService还是bindService;

startService:

Intent service = new Intent(mContext , LBSForegService.class);
startService(service); //启动

stopService(service);  //关闭

startService这种方式启动之后,该Service就跟开启他的Activity 没有关系了,该Activity关闭后Service不受影响;

首次startService时的生命周期:onCreate - onStartCommand ;

再次或多次(该Service已经在运行)startService的生命周期:只执行onStartCommand;不再执行onCreate;

调用stopSrevice关闭服务时:执行 onDestroy ;

bindService:

Service中:

    private final IBinder mBinder = new LBSForegBinder();

    public class LBSForegBinder extends Binder {
       public LBSForegService getService() {
            return LBSForegService.this;
        }
    }


        @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
绑定服务:

       Intent intent = new Intent(mContext , LBSForegService.class);
       ServiceConnection serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                LBSForegService.LBSForegBinder binder = (LBSForegService.LBSForegBinder) iBinder;
               LBSForegService lbsService = binder.getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                lbsService = null;
            }
        };
        bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);



解绑服务:

      if (serviceConnection != null)unbindService(serviceConnection);

bindService这种方式启动,注意 :如果在Activity关闭前不解绑 unindService,会报错;

首次调用bindService时的生命周期:onCreate - onBind;

再次或多次(该Service已经在运行)bindService的生命周期:不再执行onCreate和onBind;

调用unbindService会执行onUnbind、onDestroy;

 

startService&bindService 混合开启服务:

场景:在activity中想要调用service中的方法,当activity关闭后service仍然存活;

Intent intent = new Intent(mContext , LBSForegService.class);
startService(intent);
bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);

生命周期:onCreate-onStartCommand-onBind

Intent intent = new Intent(mContext , LBSForegService.class);
bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
startService(intent);

生命周期:onCreate-onBind-onStartCommand

两种方式开启,onCreate方法都会只执行一次;

注意:如果在Activity关闭前不解绑 unindService,会报错;调用unindService方法后Service只执行onUnbind不会执行onDestroy

 

前台服务:

场景:APP关闭后不希望Service被系统回收,会有通知栏显示,点击可以进入APP;(用户主动清理任务会被回收)

 startForeground(1 , buildNotification()); //提升服务为前台服务
stopForeground(true); //关闭前台服务(不会结束服务)
    private static final String NOTIFICATION_CHANNEL_NAME = "LBSbackgroundLocation";
    private NotificationManager notificationManager = null;
    boolean isCreateChannel = false;
    @SuppressLint("NewApi")
    private Notification buildNotification() {

        Notification.Builder builder = null;
        Notification notification = null;
        if(android.os.Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改,如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager = (NotificationManager) BaseApplication.get().getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId =  BaseApplication.get().getPackageName();
            if(!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder( BaseApplication.get().getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder( BaseApplication.get().getApplicationContext());
        }
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(AndroidUtils.getAppName(BaseApplication.get()))
                .setContentText("正在后台运行")
                .setContentIntent(PendingIntent.getActivity(this, 0, this.getPackageManager().getLaunchIntentForPackage(this.getPackageName()), PendingIntent.FLAG_UPDATE_CURRENT))
                .setWhen(System.currentTimeMillis());

        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }

OK!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值