Service

Service 是 Android 四大组件之一(Activity 活动,Service 服务,ContentProvider 内容提供者,BroadcastReceiver 广播),与Activity相比,Activity 是运行在前台,用户可以看得见,Service 则是运行在后台,无用户界面,用户无法看到。Service主要用于组件之间交互(例如:与Activity、ContentProvider、BroadcastReceiver进行交互)、后台执行耗时操作等(例如下载文件,播放音乐等,但Service在主线程运行时长不能超过20s,否则会出现ANR,耗时操作一般建议在子线程中进行操作)。通过本章学习可以基本掌握Service 相关知识点。

1.Service 的生命周期

Service 继承关系如下:

java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.app.Service

1.Service 生命周期

  • 两种 Service 模式 ,对应两种不同生命周期

1.启动服务

通过 startService() 启动,此服务可以在后台一直运行,
不随启动组件的消亡而消亡,只能执行单一操作,无法返回结果给调用方。
常用于网络下载、上传文件

2.绑定服务

通过绑定组件(Activity等)调用 bindService() 启动,此服务随绑定组件的消亡而解除绑定,
如果此时没有其它通过startService()启动,则此服务会随绑定组件的消亡而消亡。
多个组件不仅可以同时绑定一个服务,而且可以通过进程间通信(IPC)执行跨进程操作等。

3.两种服务可以同时运行

  只有解除绑定后,才可以销毁服务,否则会引起异常。
  • 两种 Service 模式的生命周期图如下:

    0?wx_fmt=png

    Service 生命周期图

2.四大组件之一,必须在Androidmainfest.xml 中注册

  • 注册方法如下:

<manifest ... >
  ...
  <application ... >
      <service android:name=".ServiceMethods" />
      ...
  </application>
</manifest>

如不注册 不会报异常,但是服务会起不来

3.启动服务

  • 组件启动服务的方法

        Intent  mBindIntent = new Intent(ServiceMethods.this, BindServiceMethods.class);
        startService(mStartIntent);
  • 启动服务的生命周期

01-03 17:16:36.147 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onCreate----
01-03 17:16:36.223 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onStartCommand----
01-03 17:16:38.174 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onDestroy----
  • 启动服务的Demo

package com.android.program.programandroid.component.Service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.android.program.programandroid.R;

/**
 * Created by wangjie on 2017/9/7.
 * please attention weixin get more info
 * weixin number: ProgramAndroid
 * 微信公众号: 程序员Android
 */
public class StartServiceMethods extends Service {
    private static final String TAG = "StartService wjwj:";

    public StartServiceMethods() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "----onCreate----");
//        获取NotificationManager实例
        NotificationManager notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        实例化NotificationCompat.Builder并设置相关属性
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
//                设置小图标
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//                设置通知标题
                .setContentTitle("我是通过StartService服务启动的通知")
//                设置通知不能自动取消
                .setAutoCancel(false)
                .setOngoing(true)
//                设置通知时间,默认为系统发出通知的时间,通常不用设置
//                .setWhen(System.currentTimeMillis())
//               设置通知内容
                .setContentText("请使用StopService 方法停止服务");

        //通过builder.build()方法生成Notification对象,并发送通知,id=1
        notifyManager.notify(1, builder.build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "----onStartCommand----");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "----onDestroy----");
        super.onDestroy();
    }
}

4. 绑定服务

  • 组件启动绑定服务的方法

//    绑定服务连接处理方法
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder=(MyBinder)service;
            mBindCount=myBinder.getBindCount();
            mUnBindCount=myBinder.getUnBindCount();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
//    绑定服务的方法
   bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE);

绑定服务随绑定组件的消亡而消亡

  • 绑定服务的生命周期

01-03 20:32:59.422 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onCreate----
01-03 20:32:59.423 13306-13306/com.android.program.programandroid I/BindService wjwj:: -----onBind-----
01-03 20:33:09.265 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onUnbind----
01-03 20:33:09.266 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onDestroy----
  • 绑定服务Demo

  • 绑定服务类

package com.android.program.programandroid.component.Service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BindServiceMethods extends Service {
    private static final String TAG = "BindService wjwj:";

    public BindServiceMethods() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "----onCreate----");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "----onBind----");

        MyBinder myBinder = new MyBinder();
        return myBinder;
    }


    @Override
    public boolean onUnbind(Intent intent) {

        Log.i(TAG, "----onUnbind----");
        return super.onUnbind(intent);

    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "----onDestroy----");
        super.onDestroy();
    }
}
  • 组件与绑定服务类之间的交互

 //    启动绑定服务处理方法
    public void BtnStartBindService(View view) {

        bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        isBindService = true;
        Toast.makeText(ServiceMethods.this,"启动 "+mBindCount+" 次绑定服务",Toast.LENGTH_SHORT).show();
    }

    //    解除绑定服务处理方法
    public void BtnSopBindService(View view) {
        if (isBindService) {
            unbindService(serviceConnection);
            Toast.makeText(ServiceMethods.this,"解除 "+mUnBindCount+" 次绑定服务",Toast.LENGTH_SHORT).show();
            isBindService=false;
        }

    }
  • 组件之间交互所需的 Binder 接口类

/**
* 该类提供 绑定组件与绑定服务提供接口
* */
public class MyBinder extends Binder {
   private int count = 0;

    public int getBindCount() {
        return ++count;
    }
    public int getUnBindCount() {
        return count> 0 ? count-- : 0;
    }
}

5. 提高服务的优先级

服务默认启动方式是后台服务,可以通过设置服务为前台服务,提高服务的优先级,进而防止手机内存紧张时,服务进程被杀掉。

注意: 设置前台服务主要使用以下两种方法

  • 前台服务Demo

package com.android.program.programandroid.component.Service;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.android.program.programandroid.R;

public class MyStartForcegroundService extends Service {

    public MyStartForcegroundService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

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

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

        if (intent.getAction().equals("start_forceground_service")) {

//        获取NotificationManager实例
            NotificationManager notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        实例化NotificationCompat.Builder并设置相关属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
//                设置小图标
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//                设置通知标题
                    .setContentTitle("我是通过startForeground 启动前台服务通知")
//                设置通知不能自动取消
                    .setAutoCancel(false)
                    .setOngoing(true)
//                设置通知时间,默认为系统发出通知的时间,通常不用设置
//                .setWhen(System.currentTimeMillis())
//               设置通知内容
                    .setContentText("请使用stopForeground 方法改为后台服务");

            //通过builder.build()方法生成Notification对象,并发送通知,id=1
//        设置为前台服务
            startForeground(1, builder.build());

        } else if (intent.getAction().equals("stop_forceground_service")) {
            
            stopForeground(true);
        }

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

6. 使用AIDL接口实现远程绑定

由于内容较多,后续另开一篇详细介绍。

### Service的生命周期和状态 Service在Android系统中可以分为两种主要状态:启动状态和绑定状态。当一个Service被启动后,它会在后台长时间运行,即使启动它的组件已经被销毁,Service仍然可以继续运行[^2]。如果一个Service既被启动又被绑定,那么它会同时处于这两种状态。 ### Service的生命周期方法 自定义的Service需要继承`Service`基类,并且通常需要重写一些生命周期方法来实现特定的功能: - `onCreate()`:当Service第一次创建时调用。如果Service已经存在,则不会调用此方法。 - `onStartCommand(Intent intent, int flags, int startId)`:当其他组件通过调用`startService()`方法请求启动Service时调用。在这个方法里可以处理长时间运行的操作。 - `onBind(Intent intent)`:当其他组件通过调用`bindService()`方法绑定到Service时调用。该方法返回一个`IBinder`接口,允许客户端与Service进行通信。 - `onUnbind(Intent intent)`:当所有绑定到Service的客户端都解绑后调用。 - `onDestroy()`:当Service不再使用并被销毁时调用。这是释放资源的好时机。 ### 启动状态下的Service 当一个Service通过调用`startService()`方法启动时,它进入启动状态。在这种状态下,Service独立于启动它的组件运行,直到它自己停止或被系统终止。要停止这样的Service,可以在Service内部调用`stopSelf()`方法,或者从外部组件调用`stopService()`方法[^1]。 ### 绑定状态下的Service 当组件通过调用`bindService()`方法绑定Service时,Service进入绑定状态。此时,组件可以通过`ServiceConnection`对象获取到Service提供的`IBinder`对象,从而与Service进行交互。绑定状态下的Service可以被多个组件绑定,只有当所有绑定的组件都解绑后,Service才会被销毁[^3]。 ### Service的声明 无论哪种类型的Service,都需要在`AndroidManifest.xml`文件中声明。声明格式如下: ```xml <service android:name=".Demo2Service" /> ``` 其中`.Demo2Service`是你的Service类名[^2]。 ### Service的绑定过程 为了与Service进行交互,组件需要创建一个`ServiceConnection`实例,并实现其`onServiceConnected()`和`onServiceDisconnected()`回调方法。例如: ```java private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // 这里 IBinder类型的service 就是我们要绑定的那个service // 通过这个service,Activity就可以调用MyBindService.MyBinder中的方法 } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "onServiceDisconnected: "); } }; ``` 然后,组件可以通过调用`bindService()`方法来绑定Service,并在不需要时调用`unbindService()`方法来解绑[^5]。 ### Service的应用场景 Service非常适合用来执行那些不需要用户界面但需要长时间运行的任务。比如播放音乐、下载文件、处理网络请求等。此外,Service还可以与其他组件进行交互,包括跨进程通信(IPC)[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值