public class MainActivity extends AppCompatActivity implements OnClickListener {
private Intent mServiceIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_start_Service).setOnClickListener(this);
findViewById(R.id.btn_stop_Service).setOnClickListener(this);
mServiceIntent = new Intent();
mServiceIntent.setComponent(
new ComponentName(“com.zhuanghongji.startservicefromanotherapp”,
“com.zhuanghongji.startservicefromanotherapp.AppService”));
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_Service:
startService(mServiceIntent);
break;
case R.id.btn_stop_Service:
stopService(mServiceIntent);
break;
}
}
}
分别点击两个按钮同样可以看到输出的日志:
我们也可以在Service中重写 onStartCommand() 来接收其他应用传递过来的数据。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
// 做你想做的事
}
三、跨应用绑定Service
1. 创建AIDL文件
右键app包名新建.aidl文件:
-
自动生成的代码如图中右边所示(IAppServiceRemoteBinder.aidl)。
-
同时也自动新建了个aidl文件夹,.aidl文件就是在这个文件夹下(图中左边)。
Build->Make Project 发现在…debug目录下自动生成了对应的java接口文件
该文件代码如下:
/*
-
This file is auto-generated. DO NOT MODIFY.
-
Original file: F:\AndroidG\StartServiceFromAnotherApp\app\src\main\aidl\com\zhuanghongji\startservicefromanotherapp\IAppServiceRemoteBinder.aidl
*/
package com.zhuanghongji.startservicefromanotherapp;
// Declare any non-default types here with import statements
public interface IAppServiceRemoteBinder extends android.os.IInterface {
/**
- Local-side IPC implementation stub class.
*/
public static abstract class Stub extends android.os.Binder implements com.zhuanghongji.startservicefromanotherapp.IAppServiceRemoteBinder {
private static final java.lang.String DESCRIPTOR = “com.zhuanghongji.startservicefromanotherapp.IAppServiceRemoteBinder”;
/**
- Construct the stub at attach it to the interface.
*/
<