下面是5+的代码
var mainActivity = plus.android.runtimeMainActivity();
var Intent = plus.android.importClass('android.content.Intent');
var intent = new Intent();
intent.setClassName(mainActivity, 'cn.com.victorysoft.spb.KeepAliveService')
var Bundle = plus.android.importClass('android.os.Bundle');
var bundle = new Bundle();
bundle.putString("user_id", VSAuth.getAuthInfo().permission.userId);//传参数,从service的onStartCommand中接收intent
intent.putExtras(bundle);
mainActivity.startForegroundService(intent)
//以上代码亲自试验过,注意需要 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
权限
下面是service的后台部分代码
private static final String CHANNEL_ID = "keep_alive";
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_NAME = "驻留服务";
private static final String NOTIFICATION_TITLE = "服务运行中";
private static final String NOTIFICATION_CONTENT_TEXT = "已开启驻留服务";
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 创建通知
createNotification();
//接收参数
String user_id = intent.getStringExtra("user_id");
return START_STICKY;//表示Service在被系统杀死后会自动重启
}
private void createNotification() {
//前台通知显示
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;//优先级
NotificationCompat.Builder builder = null;
//Android8.0之后和之前的通知有很大的差异
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, NOTIFICATION_NAME, importance);
channel.enableLights(true);
channel.setLightColor(Color.RED);
manager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setOngoing(true)// 用户无法取消----不好使
.setSmallIcon(R.drawable.icon)//图标
.setContentTitle(NOTIFICATION_TITLE)
.setContentText(NOTIFICATION_CONTENT_TEXT)
.setWhen(System.currentTimeMillis());
} else {
builder = new NotificationCompat.Builder(this)
.setOngoing(true)// 用户无法取消----不好使
.setSmallIcon(R.drawable.icon)
.setContentTitle(NOTIFICATION_TITLE)
.setContentText(NOTIFICATION_CONTENT_TEXT)
.setWhen(System.currentTimeMillis());
}
Notification notification = builder.build();
// 用户无法取消----不好使
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(NOTIFICATION_ID, notification);
}
d***@163.com
解决了吗,楼主
2023-05-31 15:34