下面是启动前台服务的代码。它适用于三星、moto、Vivo、Oppo 等许多设备,也适用于 Android 版本的牛轧糖和奥利奥,但不适用于一加设备。谁能告诉我是否需要任何额外的更改或许可才能在一加设备中运行,或者是否有任何模拟器支持一加手机。
public class ForegroundService extends Service {
private Context ctx;
private static final String PRIMARY_NOTIF_CHANNEL = "default";
@Override
public void onCreate() {
super.onCreate();
ctx = this;
createNotificationService();
}
private void createNotificationService(){
TelephonyManager mTelephonyManager = (TelephonyManager) ctx.getSystemService(TELEPHONY_SERVICE);
if(mTelephonyManager != null)
mTelephonyManager.listen(new CellTowerStateListener(ctx), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
RemoteViews notificationView = new RemoteViews(this.getPackageName(), R.layout.notification);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setupChannel();
}
Notification notification = new NotificationCompat.Builder(this, PRIMARY_NOTIF_CHANNEL)
.setSmallIcon(R.mipmap.ic_launcher)
.setColor(Color.parseColor("#00f6d8"))
.setContent(notificationView)
.setPriority(Notification.PRIORITY_MIN)
.setOngoing(true).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_REDELIVER_INTENT;
}
private void setupChannel(){
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel chan1;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
chan1 = new NotificationChannel(
PRIMARY_NOTIF_CHANNEL,
PRIMARY_NOTIF_CHANNEL,
NotificationManager.IMPORTANCE_NONE);
chan1.setLightColor(Color.TRANSPARENT);
chan1.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
if(notificationManager != null)
notificationManager.createNotificationChannel(chan1);
}
}
@Override
public IBinder onBind(Intent intent) {
// Used only in case of bound services.
return null;
}
}