Служба уведомлений Foreground не работает на одном устройстве плюс - PullRequest
0 голосов
/ 04 декабря 2018

Ниже приведен код для запуска службы переднего плана.Он отлично работает для многих устройств, таких как Samsung, Moto, Vivo, Oppo, а также с нуга и oreo версии Android, но не работает на устройствах 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;
}

}

1 Ответ

0 голосов
/ 18 мая 2019

Итак, я решил этот вопрос всего час назад:

Манифест

<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, Xiaomi и Samsung, когда яВ автономном режиме отслеживания использовалось от 50 до 60% ЦП.обнаружил, что это были некоторые потоки, которые я назвал прерыванием, но они все еще работали

после того, как научились использовать, начните записывать фрагменты своего приложения и анализировать их, у вас есть 2 хороших варианта для запуска:

  • Примеры методов Java

  • Методы трассировки Java

Android Logcat рад видеть, что BG обнаруживает oneplus, пытающийся удалить вашсервис и, если нужно, ваше приложение.

PS: BGDetect устраняет без страха.Мне нужно, чтобы моя производительность отслеживания как в Интернете, так и в автономном режиме составляла в среднем от 20% до 30% в приложении и от 15% до 20% во сне до того, как OnePlus и Oppo перестанут убивать меня, не давая мне возможности перезагрузить свой сервис.

Как вы, наверное, уже заметили, когда эти ОС хотят убить что-то, что они запускают из приложения, а не из службы, имейте в виду: НЕ СВЯЗАТЬ приложение с СЕРВИСОМ, если вы делаете это, я не знаю почему, но ОСеще более безжалостен.

BG-Detect слишком много -> они должны были предупредить разработчиков Android при повторной реализации функции

PPS Это слишком много, но я беру свою шляпу OnePlusBugHunters, его чертовски хорошо реализовано.

Надеюсь, что смогу помочь.

протестировано на OP3 Oreo 8.0.1

Отредактировано

OnePlus при перезагрузке снова оптимизирует ваше приложение.Тестирую, чтобы исправить ошибку

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...