一加手机中前台通知服务无法正常工作

6
以下是开始前台服务的代码。 它在许多设备上运行良好,如三星、moto、Vivo、Oppo和Android版本nougat和oreo,但不能在One plus设备上运行。 有人能告诉我是否需要进行任何额外的更改或权限才能在One plus设备上运行,或者是否有任何模拟器支持One plus手机吗?
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;
}

}


前台状态是指应用程序是打开、关闭还是终止? - R15
如果有错误,请检查您的控制台。 - Nouman Ch
一加手机运行的是哪个安卓版本? - Nouman Ch
@CGPA6.4 应用程序会关闭,因为我的应用程序没有任何用户界面。它作为后台服务行为,只显示通知。 - surbhi verma
@NoumanCh - 安卓版本为:OxygenOS Open Beta 17 | Android 8.1。由于没有任何模拟器支持一加设备,我无法检查日志。 - surbhi verma
遇到完全相同的问题。@surbhiverma,你找到任何解决方案了吗?在一加手机上不起作用,在其他设备上可以。如果有人找到解决方案,请建议一下。 - Topsy
2个回答

8

我刚刚一个小时前解决了这个问题:

清单

<application
    android:name=".AppNotification"
    android:allowBackup="true"
    android:icon="@mipmap/pro_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/pro_icon"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
<service
        android:name=".services.TrackingBackgroundService"
        android:enabled="true"
        android:exported="true" />

应用程序 - 创建通知渠道

public class AppNotification extends Application {

public static final String CHANNEL_ID = "AppNotificationChannel";
private void CreateNotificationChannel() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel serviceChannel = new NotificationChannel(
                CHANNEL_ID,
                "App Notification",
                NotificationManager.IMPORTANCE_HIGH
        );
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}

}

活动

首先你需要要求用户禁用电池优化:

Intent intent = new Intent();
    String packageName = this.getPackageName();
    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (pm.isIgnoringBatteryOptimizations(packageName))
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
    else {
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + packageName));
        startActivity(intent);
    }

那么你需要像这样启动服务以处理不同的版本:

public void startService() {
    Intent serviceIntent = new Intent(InitSkipperActivity.this, TrackingBackgroundService.class);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(serviceIntent);
    } else {
        startService(serviceIntent);
    }
}

服务

public class TrackingBackgroundService extends Service {

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Intent notificationIntent = new Intent(this, TrackingActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("title")
            .setContentText("content")
            .setSmallIcon(R.mipmap.pro_icon)
            .setPriority(5)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(1, notification);

    return START_STICKY;
}

之后,您需要使用Android分析器测试您的服务:

我的应用在Oppo、OnePlus、小米和三星设备上异常地占用CPU。当我离线跟踪时,发现使用了50%到60%的CPU。我发现是一些我调用过interrupt但仍在运行的线程。

学会使用后,开始记录您的应用程序并进行分析,有两个很好的选项可供选择:

  • Java方法样本

  • Java方法跟踪

Android Logcat很好地看到了OnePlus尝试删除您的服务以及必要时删除您的应用程序的背景检测。

附言:BGDetect毫不留情地消除。我需要将我的在线和离线追踪性能都提高到应用程序中的20%到30%,睡眠中为15%到20%,才能使OnePlus和Oppo停止无法重启我的服务。

如您可能已经注意到的那样,当这些操作系统想要杀死某些东西时,它们从应用程序开始而不是从服务开始,请记住:如果您绑定应用程序到服务,则我不知道为什么,但是操作系统会更加无情。

BG-Detect太过分了->重新实现该功能时,他们应该向Android开发人员提供警告。

附言:这太过分了,但我向OnePlus BugHunters致敬,它实现得非常好。

希望我能有所帮助。

在OP3 Oreo 8.0.1上测试通过。

编辑:

OnePlus在重新启动时将您的应用程序设置为优化模式。正在测试解决这个问题。


嗨@rmindzstar,你已经为一加设备修复了吗?我在使用安卓10操作系统的一加手机上遇到了同样的问题。 - mdroid
只有在所有这些设置都完成,并且CPU使用率低于10%时,才能正常运行。在Android 9上,超过12%就会关闭。虽然找不到真正的“关键”,但在所有其他设备上都可以正常运行。 - rmindzstar
现在它发出了一个警告:“使用 REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 违反了Play商店关于可接受使用情况的内容政策,具体描述请参阅 https://developer.android.com/training/monitoring-device-state/doze-standby.html”。当我尝试时也会出现“获取软件包信息错误:com.”。 - BPDev
现在它会发出一个警告:"使用REQUEST_IGNORE_BATTERY_OPTIMIZATIONS违反了Play Store内容政策,该政策涉及可接受的使用情况,详见https://developer.android.com/training/monitoring-device-state/doze-standby.html"。当我尝试时,还会出现"获取包信息出错:com."。 - undefined

0

使用我的方法在所有设备上工作

 private void checkOptimization() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String packageName = getApplicationContext().getPackageName();
        PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        if (pm != null) {
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接