服务(笔记)

做个记录

1、启动一个简单的服务

启动和停止服务

Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 启动服务
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务

停止服务还可以在继承Service的类里面调用stopself方法来停止

至于MyService类,继承Service并重写onBind(必须要的),onCreate,onDestroy,onStartCommand(执行逻辑)方法,并在Androidmanifest文件注册就可以使用

 

2、启动一个Bind服务

绑定活动与服务,增加联系,例子:下载任务

服务后台下载,活动获取服务中的下载进度

思路:在MyService中新建一个内部类,继承Binder,利用onBind方法返回对象并调用内部类的方法

绑定服务与活动:

Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE); // 绑定服务
unbindService(connection); // 解绑服务

其中connection是ServiceConnection对象

private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
        }
    };

模拟下载的内部类:

    class DownloadBinder extends Binder {

        public void startDownload() {
            Log.d(TAG, "startDownload executed");
            synchronized ((Object) progress){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i=0; i<100; i++) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                Log.d(TAG, "run: error");
                            }
                            progress++;
                        }
                    }
                }).start();
            }
        }

        public int getProgress() {
            Log.d(TAG, "Progress:"+progress);
            return progress;
        }
    }

3、前台服务

前台服务可以防止因为系统内存不足被回收

只需在继承Service的类中的onCreate方法中加入下面的代码即可

Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("This is content title")
                .setContentText("This is content text")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .build();
        startForeground(1, notification);

 

GitHub:https://github.com/1938316175/ServiceTest

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值