HarmonyOS-Service&Android-Service(1)

public class HarmonyOSService extends Ability {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
}

@Override
public void onCommand(Intent intent, boolean restart, int startId) {
super.onCommand(intent, restart, startId);
}

@Override
public IRemoteObject onConnect(Intent intent) {
super.onConnect(intent);
return null;
}

@Override
public void onDisconnect(Intent intent) {
super.onDisconnect(intent);
}

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

Android:

public class AndroidService extends Service {
@Override
public void onCreate() {
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}

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

@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}

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

初始化:

  • onStart():HarmonyOS创建Service的时候调用,用于Service的初始化,在Service的整个生命周期只会调用一次。
  • onCreate():Android首次创建服务时,系统会(在调用 onStartCommand() 或 onBind() 之前)调用此方法来执行一次性设置程序。如果服务已在运行,则不会调用此方法。

启动:

  • onCommand():HarmonyOS在Service创建完成之后调用,该方法在客户端每次启动该Service时都会调用,用户可以在该方法中做一些调用统计、初始化类的操作。
  • onStartCommand() :Android中当另一个组件(如 Activity)请求启动服务时,系统会通过调用 startService() 来调用此方法。执行此方法时,服务即会启动并可在后台无限期运行。实现此方法,则在服务工作完成后,则通过调用 stopSelf() 或 stopService() 来停止服务。(如果只想绑定,则无需实现此方法。)

绑定:

  • onConnect():HarmonyOS中在Ability和Service连接时调用,该方法返回IRemoteObject对象,用户可以在该回调函数中生成对应Service的IPC通信通道,以便Ability与Service交互。Ability可以多次连接同一个Service,系统会缓存该Service的IPC通信对象,只有第一个客户端连接Service时,系统才会调用Service的onConnect方法来生成IRemoteObject对象,而后系统会将同一个RemoteObject对象传递至其他连接同一个Service的所有客户端,而无需再次调用onConnect方法。
  • onBind():Android中当另一个组件想要与服务绑定(例如执行 RPC)时,系统会通过调用 bindService() 来调用此方法。在此方法的实现中,开发者必须通过返回 IBinder 提供一个接口,以供客户端用来与服务进行通信。请务必实现此方法;但是,如果开发者并不希望允许绑定,则应返回 null。

解绑:

  • onDisconnect() :HarmonyOS中在Ability与绑定的Service断开连接时调用。
  • onUnbind():Android中客户端可通过调用 unbindService() 关闭连接。多个客户端可以绑定到相同服务,而且当所有绑定全部取消后,系统即会销毁该服务。(服务不必自行停止运行。)

销毁:

  • onStop():HarmonyOS中在Service销毁时调用。Service应通过实现此方法来清理任何资源,如关闭线程、注册的侦听器等。
  • onDestroy():Android中当不再使用服务且准备将其销毁时,系统会调用此方法。服务应通过实现此方法来清理任何资源,如线程、注册的侦听器、接收器等。这是服务接收的最后一个调用。 总而言之,不管是HarmonyOS还是Android,有关Service的生命周期及相关方法调用及方法作用基本一致。

使用

创建Service

HarmonyOS:创建Ability的子类,实现Service相关的生命周期方法。Service也是一种Ability,用户可以重写这些方法来添加自己的处理。

public class HarmonyOSService extends Ability {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
}

}

Android:创建 Service 的子类(或使用它的一个现有子类)。开发者需要重写一些回调方法,从而处理服务生命周期的某些关键方面,并提供一种机制将组件绑定到服务。

public class AndroidService extends Service {
@Override
public void onCreate() {
super.onCreate();
}

}

或者创建IntentService(Service 子类)子类,串行执行所有启动服务请求。

public class AndroidIntentService extends IntentService {

public AndroidIntentService() {
super(“AndroidIntentService”);
}
@Override
protected void onHandleIntent(Intent intent) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
}

注册

HarmonyOS:Service需要在应用配置文件中进行注册,注册类型type需要设置为service。

{
“module”: {
“abilities”: [
{
“name”: “.ServiceAbility”,
“type”: “service”,
“visible”: true

}
]

}

}

Android:开发者必须在应用的清单文件中声明所有服务。如要声明服务,需要添加 元素作为 元素的子元素,name属性是唯一必需的属性。

<manifest … >

<application … >



启动服务

HarmonyOS

HarmonyOS中Ability为开发者提供了startAbility()方法来启动另外一个Ability。因为Service也是Ability的一种,开发者同样可以通过将Intent传递给该方法来启动Service。不仅支持启动本地Service,还支持启动远程Service。其中启动本地服务如下:

Intent intent = new Intent();
Operation operation = new Intent.OperationBuilder()
.withDeviceId(“”)
.withBundleName(“com.huawei.hiworld.himusic”)
.withAbilityName(“com.huawei.hiworld.himusic.entry.ServiceAbility”)
.build();
intent.setOperation(operation);
startAbility(intent);

参数说明:

  • DeviceId:表示设备ID。如果是本地设备,则可以直接留空;如果是远程设备,可以通过ohos.distributedschedule.interwork.DeviceManager提供的getDeviceList获取设备列表。
  • BundleName:表示包名称。
  • AbilityName:表示待启动的Ability名称。 启动远程服务如下:

Operation operation = new Intent.OperationBuilder()
.withDeviceId(“deviceId”)
.withBundleName(“com.huawei.hiworld.himusic”)
.withAbilityName(“com.huawei.hiworld.himusic.entry.ServiceAbility”)
.withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) // 设置支持分布式调度系统多设备启动的标识
.build();
Intent intent = new Intent();
intent.setOperation(operation);
startAbility(intent);

Ability将通过startAbility() 方法来启动Service。 如果Service尚未运行,则系统会先调用onStart()来初始化Service,再回调Service的onCommand()方法来启动Service。 如果Service正在运行,则系统会直接回调Service的onCommand()方法来启动Service。

Android

开发者可以通过将 Intent 传递给 startService() 或 startForegroundService(),从 Activity 或其他应用组件启动服务。Android 系统会调用服务的 onStartCommand() 方法,并向其传递 Intent,从而指定要启动的服务。如果应用面向 API 级别 26 或更高版本,除非应用本身在前台运行,否则系统不会对使用或创建后台服务施加限制。如果应用需要创建前台服务,则其应调用 startForegroundService()。此方法会创建后台服务,但它会向系统发出信号,表明服务会将自行提升至前台。创建服务后,该服务必须在五秒内调用自己的 startForeground() 方法。

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

startService() 方法会立即返回,并且 Android 系统会调用服务的 onStartCommand() 方法。如果服务尚未运行,则系统首先会调用 onCreate(),然后调用 onStartCommand()。 如果服务亦未提供绑定,则应用组件与服务间的唯一通信模式便是使用 startService() 传递的 Intent。但是,如果开发者希望服务返回结果,则启动服务的客户端可以为广播(通过 getBroadcast() 获得)创建一个 PendingIntent,并将其传递给启动服务的 Intent 中的服务。然后,服务便可使用广播传递结果。 多个服务启动请求会导致多次对服务的 onStartCommand() 进行相应的调用。但是,如要停止服务,只需一个服务停止请求(使用 stopSelf() 或 stopService())即可。

启动前台服务(可选)

HarmonyOS

开发者只需在Service创建的方法里,调用keepBackgroundRunning()将Service与通知绑定。调用keepBackgroundRunning()方法前需要在配置文件中声明。ohos.permission.KEEP_BACKGROUND_RUNNING权限,该权限是normal级别,同时还需要在配置文件中添加对应的backgroundModes参数。在onStop()方法中调用cancelBackgroundRunning​()方法可停止前台Service。使用前台Service的onStart()代码示例如下:

// 创建通知,其中1005为notificationId
NotificationRequest request = new NotificationRequest(1005);
NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
content.setTitle(“title”).setText(“text”);
NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
request.setContent(notificationContent);

// 绑定通知,1005为创建通知时传入的notificationId
keepBackgroundRunning(1005, request);

在配置文件中配置如下:

{
“name”: “.ServiceAbility”,
“type”: “service”,
“visible”: true,
“backgroundModes”: [“dataTransfer”,“location”]
}

Android

开发者创建前台服务,需要调用startForeground(),这个方法同样需要notificationId和Notification实例:

Intent notificationIntent = new Intent(this, AndroidActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build();
startForeground(ONGOING_NOTIFICATION_ID, notification);

注意:Notification ID不能为0,同时在Android 9 (API level 28) 获取更高版本中前台服务需要申明:FOREGROUND_SERVICE权限:

<manifest xmlns:android=“http://schemas.android.com/apk/res/android” …>

<application …>


如果应用目标level高于Android 10 (API level 29) 在清单文件中还要申明相关前台服务类型:

...

代码中也要申明:

Notification notification = …;
Service.startForeground(notification,
FOREGROUND_SERVICE_TYPE_LOCATION | FOREGROUND_SERVICE_TYPE_CAMERA);

绑定服务(可选)

HarmonyOS

如果Service需要与Page Ability或其他应用的Service Ability进行交互,则应创建用于连接的Connection。Service支持其他Ability通过connectAbility()方法与其进行连接。 在使用connectAbility()处理回调时,需要传入目标Service的Intent与IAbilityConnection的实例。IAbilityConnection提供了两个方法供开发者实现:onAbilityConnectDone()用来处理连接的回调,onAbilityDisconnectDone()用来处理断开连接的回调。

// 创建连接回调实例
private IAbilityConnection connection = new IAbilityConnection() {
// 连接到Service的回调
@Override
public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int resultCode) {
// 在这里开发者可以拿到服务端传过来IRemoteObject对象,从中解析出服务端传过来的信息
}

// 断开与连接的回调
@Override
public void onAbilityDisconnectDone(ElementName elementName, int resultCode) {
}
};
// 连接Service
connectAbility(intent, connection);

同时,Service侧也需要在onConnect()时返回IRemoteObject,从而定义与Service进行通信的接口。onConnect()需要返回一个IRemoteObject对象,HarmonyOS提供了IRemoteObject的默认实现,用户可以通过继承RemoteObject来创建自定义的实现类。Service侧把自身的实例返回给调用侧的代码示例如下:

// 创建自定义IRemoteObject实现类
private class MyRemoteObject extends RemoteObject {
public MyRemoteObject() {
super(“MyRemoteObject”);
}
}

// 把IRemoteObject返回给客户端
@Override
protected IRemoteObject onConnect(Intent intent) {
return new MyRemoteObject();
}

Android

绑定服务是客户端-服务器接口中的服务器。借助绑定服务,组件(例如 Activity)可以绑定到服务、发送请求、接收响应,以及执行进程间通信 (IPC)。绑定服务通常只在为其他应用组件提供服务时处于活动状态,不会无限期在后台运行。创建提供绑定的服务时,您必须提供 IBinder,进而提供编程接口,以便客户端使用此接口与服务进行交互。开发者可以通过三种方法定义接口:扩展 Binder 类,使用 Messenger,使用 AIDL(一般不用)。

  • 扩展 Binder 类。创建代码如下:

public class LocalService extends Service {
private final IBinder binder = new LocalBinder();
private final Random mGenerator = new Random();

public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}

public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}

启动如下:

public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;

@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, LocalService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
super.onStop();
unbindService(connection);
mBound = false;
}
public void onButtonClick(View v) {
if (mBound) {
int num = mService.getRandomNumber();

}
}

private ServiceConnection connection = new ServiceConnection() {

@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
3123450)]

[外链图片转存中…(img-ucZnL2ZT-1715623123452)]

[外链图片转存中…(img-SjQQlT8Z-1715623123458)]

[外链图片转存中…(img-IXzhwzPZ-1715623123459)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值