Android Service

一、简介

Service是Android的四大组件之一,它可以使应用程序保持在后台运行,它非常适合去执行那些不需要和用户交互而且长期运行的任务,服务的运行不依赖于任何用户界面,即使程序被切换到后台,或者用户打开了另外一个应用程序,服务仍然能够保持正常运行。

二、创建服务

新建一个类,继承Service

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

public class MyService extends Service {

    public MyService(){
        
    }

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

在配置文件中注册

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />

三、独立的服务(生命周期和进程一致)

启动服务

        Intent intent = new Intent(this,MyService.class);
        startService(intent);

关闭服务

        Intent intent = new Intent(this,MyService.class);
        stopService(intent);
        stopSelf(); //服务内部调用

四、活动与服务通信(生命周期和活动一致)

创建与活动通信的服务

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

public class MyService extends Service {

    private MyBinder mBinder = new MyBinder();

    public MyService(){

    }

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

    class MyBinder extends Binder{
        public void start(){}
        public int getProgress(){return 0;}
        public void end(){}
    }
}

Activity中的实现

    private MyService.MyBinder mBinder;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = (MyService.MyBinder) service;
            mBinder.start(); //活动和服务通信
            mBinder.getProgress(); //活动和服务通信
        }

        @Override   
        public void onServiceDisconnected(ComponentName name) {
            mBinder.end(); //活动和服务通信
        }
    };

绑定服务

        Intent intent = new Intent(this,MyService.class);
        bindService(intent,mServiceConnection,BIND_AUTO_CREATE);

解绑服务

        unbindService(mServiceConnection);

五、前台服务

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

public class MyService extends Service {

    public MyService(){
        Intent intent = new Intent(this,MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
        Notification notification =new NotificationCompat.Builder(this) 
                .setContentTitle("通知栏标题")
                .setContentText("通知栏内容")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setContentIntent(pendingIntent)
                .build();
        //启动前台服务
        startForeground(1,notification);  // 1是通知栏的id,每个通知的id都不一样
        //在通知栏显示通知
        //NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //manager.notify(1,notification); // 1是通知栏的id,每个通知的id都不一样
    }

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

六、自动停止的服务

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;

public class MyIntentService extends IntentService {
    
    public MyIntentService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //执行逻辑,完成后,会自动停止服务,用法和普通服务一样
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 【Android Service】 Service 简介(★★★) 很多情况下,一些与用户很少需要产生交互的应用程...
    Rtia阅读 3,184评论 1 21
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,269评论 19 139
  • 前言:本文所写的是博主的个人见解,如有错误或者不恰当之处,欢迎私信博主,加以改正!原文链接,demo链接 Serv...
    PassersHowe阅读 1,466评论 0 5
  • 1.Service简介 服务是一个应用程序组件,可以在后台执行长时间运行的操作,不提供用户界面。一个应用程序组件可...
    紫豪阅读 22,092评论 11 83
  • 感觉是哧溜一声,我的乔就即将成为一名中学生了!在你成长的路上,我一直在你身边,却又感觉离你很远!我喜欢你懵懵懂懂还...
    鼹鼠之家阅读 380评论 0 4