服务启动有2种方式分别是startService 和bindService
startService 启动的服务:主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService
bindService 启动的服务:该方法启动的服务可以进行通信。停止服务使用unbindService
创建一个服务
package com.nyw.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class MyService extends Service{
public final String TAG = "log_info";
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
//服务第一次启动执行,可以在这里做初始化业务代码操作。在次启动服务只会执行onStartCommand
Log.i(TAG,"onCreate");
Log.i("SFSJFDKDSJDFKS","onCreate");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//抽象方法,仅启动服务是bindService的时候生效
Log.i(TAG,"onBind");
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//每次服务启动都执行,我们在该方法中根据传入的Intent参数进行实际的操作,比如会在此处创建一个线程用于下载数据或播放音乐等
Log.i(TAG,"onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
//服务停止会执行
super.onDestroy();
Log.i(TAG,"onDestroy");
}
}
启动服务方法一
package com.nyw.aidldemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* 测试服务打开关闭及跨进程通信
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_openServer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//打开服务
Intent startIntent = new Intent(MainActivity.this, MyService.class);
startService(startIntent);
}
});
findViewById(R.id.btn_closeServer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//关闭服务
Intent stopIntent = new Intent(MainActivity.this,MyService.class);
stopService(stopIntent);
}
});
}
}
AndroidManifest要添加服务,AS开发默认添加
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nyw.aidldemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AIDLDemo">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.nyw.aidldemo"/>
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nyw.aidldemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AIDLDemo">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.nyw.aidldemo"/>
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
启动外面其他APP服务,可以在启动服务的时候使用setComponent
intent.setComponent(new ComponentName("包名","通过包名访问到服务"))
方法二
添加服务
package com.nyw.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service implements IMyAidlInterface{
public final String TAG = "log_info";
//client 可以通过Binder获取Service实例
public class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
//通过binder实现调用者client与Service之间的通信
private MyBinder binder = new MyBinder();
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
//服务第一次启动执行,可以在这里做初始化业务代码操作。在次启动服务只会执行onStartCommand
Log.i(TAG,"onCreate");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//抽象方法,仅启动服务是bindService的时候生效,activity中我们调用了bindService()后,会回调onBind()方法
Log.i(TAG,"onBind");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//每次服务启动都执行,我们在该方法中根据传入的Intent参数进行实际的操作,比如会在此处创建一个线程用于下载数据或播放音乐等
Log.i(TAG,"onStartCommand");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
//服务停止会执行
Log.i(TAG,"onDestroy");
}
//getMsg是Service暴露出去供client调用的公共方法
public String getMsg() {
String msg="Service暴露出去供client调用的公共方法";
return msg;
}
}
activity代码如下
package com.nyw.aidldemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
/**
* 测试服务打开关闭
*/
public class MainActivity extends AppCompatActivity {
private boolean isBind = false;
private MyService myService=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_openServer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//打开服务
//方法一
// Intent startIntent = new Intent(MainActivity.this, MyService.class);
// startService(startIntent);
//方法二
Intent startIntent = new Intent(MainActivity.this, MyService.class);
startIntent.putExtra("from", "Activity");
bindService(startIntent, conn, BIND_AUTO_CREATE);
}
});
findViewById(R.id.btn_closeServer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//关闭服务
//方法一
// Intent stopIntent = new Intent(MainActivity.this,MyService.class);
// stopService(stopIntent);
//方法二
if(isBind==true) {
unbindService(conn);
}
}
});
}
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
//绑定成功
isBind = true;
MyService.MyBinder myBinder = (MyService.MyBinder) binder;
myService = myBinder.getService();
Log.i("log_info", "Activity - onServiceConnected");
String msg = myService.getMsg();
Log.i("log_info", "Activity - getMsg = " + msg);
}
@Override
public void onServiceDisconnected(ComponentName name) {
//绑定失败
isBind = false;
Log.i("log_info", "Activity - onServiceDisconnected");
}
};
}
AndroidManifest要添加上服务,同上。
绑定其他APP服务,在绑定前使用setComponent就行了
intent.setComponent(new ComponentName("包名","通过包名访问到服务"))
生命周期
第一次启动绑定服务
onCreate onStartCommand
重复多次绑定服务
onStartCommand
结束绑定服务
onDestroy