Я возился со службами Android и столкнулся с проблемой при запуске Foreground Services в MIUI 10 (Устройство тестирования: Redmi note 5 pro )
В основном Сервис работает до тех пор, пока пользователь взаимодействует с активностью, но как только пользователь убивает активность, сервис переднего плана также убивается.
Я читал некоторые другие ответы относительно тех же проблем,
которые утверждают, что в таких устройствах, как Xaomi, Oppo, lenovo, LG, honor и т. д. Вам необходимо включить разрешение «Автозапуск» для приложения
, которое я пробовал безуспешно.Я также попробовал следующее, но безуспешно:
- Отключена оптимизация MIUI
- Отключено Энергосбережение
- Удалено ограничение батареи для приложения
- Освободил память (Всего: 3 ГБ, Доступно: 2 ГБ)
Для меня сработало включение: "Не сохранять активности" в Опции разработчика , но в реальных приложениях вы, вероятно, не будете просить пользователей включить эту опцию, поскольку она влияет на взаимодействие с пользователем.
ПоКстати, я тестировал свое приложение на других устройствах, таких как pixel, nexus и т. д. (эмуляторы студии Android). И все они работали нормально.Эта проблема возникает только на моем устройстве.
Ссылка на скачивание приложения для целей отладки: https://anonfile.com/d4k511p1bd/app-debug_apk
Исходный код
Файл: MainActivity.java
package com.myname.foregroundserviceexample;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText editTextInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextInput = findViewById(R.id.edit_text_input);
}
public void startService(View v) {
String input = editTextInput.getText().toString();
Intent serviceIntent = new Intent(this, ExampleService.class);
serviceIntent.putExtra("inputExtra", input);
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService(View v) {
Intent serviceIntent = new Intent(this, ExampleService.class);
stopService(serviceIntent);
}
}
Файл: ExampleService.java
package com.myname.foregroundserviceexample;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import static com.myname.foregroundserviceexample.App.CHANNEL_ID;
public class ExampleService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
// Starting Foreground Service
startForeground(1, notification);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Файл: App.java
package com.myname.foregroundserviceexample;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
IЯ знаю, что есть способ обойти это, включив опцию «Не выполнять действия» в разделе «Разработка параметров», но я искренне не хочу, чтобы пользователь включил это на своем устройстве. Также я с радостью согласился бы с любыми альтернативами или улучшениями кода для обеспечения работы службы переднего плана.в MIUI 10.
Спасибо
РЕДАКТИРОВАТЬ:
Вот ссылка на проект: https://anonfile.com/y5Rd4bp3b9/ForegroundServiceExample_zip
И это учебникЯ подписался на YouTube: https://www.youtube.com/watch?v=FbpD5RZtbCc