安卓程序:
在manifast.xml中定义service
<service
android:name=".DataService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.h5appdataprovider.dataService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
MainActivity.java的onCreate中添加:
// 创建通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("channel_androidToH5_1", "AndroidToH5Channel", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
DataService.java
public class DataService extends Service {
public DataService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 获取传递的数据
String name = intent.getStringExtra("name");
Toast.makeText(getApplicationContext(), "Data Service Started: get name = " + name, Toast.LENGTH_SHORT).show();
// 创建通知
Notification.Builder builder = new Notification.Builder(getApplicationContext());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(this, "channel_androidToH5_1");
} else {
builder = new Notification.Builder(this);
}
builder.setContentTitle("Data Service")
.setContentText("Data Service Started");
startForeground(1, builder.build());
return super.onStartCommand(intent, flags, startId);
}
}
H5启动服务:
let context = plus.android.runtimeMainActivity();
// 通过反射获取Android的Intent对象
let Intent = plus.android.importClass("android.content.Intent");
// 创建 intent
let _intent = new Intent();
// 要传递的数据
_intent.putExtra("name", "张三");
_intent.setAction("com.example.h5appdataprovider.dataService");
_intent.setPackage("com.example.h5appdataprovider");
console.log(JSON.stringify(_intent));
plus.android.requestPermissions(
["android.permission.QUERY_ALL_PACKAGES"],
function(resultObj) {
console.log("申请权限成功!");
//启动Activity
context.startForegroundService(_intent);
},
function(resultObj) {
console.log("申请权限失败!");
}
);
注意setAction要与intent-filter中的内容一致哦