How to make foreground Services work in MIUI?












0















I've been messing around with android services and facing a problem while running foreground Services in MIUI 10(Testing Device: Redmi note 5 pro)



Basically Service runs as long as the user is interacting with activity but as soon as user kills activity, foreground service also gets killed.



I read some other answers regarding the same issues,




which state that in devices like Xaomi, Oppo, lenovo, LG, honor etc.
You need to enable "AutoRun" permission for the app




Which I tried with no success. I also tried the following with no success at all:




  1. Disabled MIUI optimization

  2. Disabled Power saving

  3. Removed Battery restrictions for the app

  4. Freed the memory (Total: 3GB, Available:
    2GB)





What worked for me was enabling the: "Don't keep activites" in the Developer options but in real world application you probably wouldn't ask users to enable this option since it affects user experience.



Developer options MIUI 10



By the way, I tested my app in other devices such as pixel, nexus etc(Android studio emulators) And They all worked fine. It's only my device which is causing this issue.



Download link for the app for debugging purposes: https://anonfile.com/d4k511p1bd/app-debug_apk



Source Code



File: 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);
}

}


File: 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;
}
}


File: 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 know there's a way around this by enabling "Don't keep activities" in Developing options but I genuinely don't want the user to enable this in their device, Also I would gladly accept any alternative or code improvements to make the foreground Service work in MIUI 10.



Thankyou



EDIT:



Here's the project link: https://anonfile.com/y5Rd4bp3b9/ForegroundServiceExample_zip



And this is the tutorial I was following on YouTube: https://www.youtube.com/watch?v=FbpD5RZtbCc










share|improve this question

























  • I can't see startForeground() anywhere in your service.

    – egoldx
    Jan 2 at 16:05













  • @egoldx Actually startForeground() is there in the original code, I must've accidentally removed it while uploading source code in here. But yeah It is there in the ExampleService.java

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:39
















0















I've been messing around with android services and facing a problem while running foreground Services in MIUI 10(Testing Device: Redmi note 5 pro)



Basically Service runs as long as the user is interacting with activity but as soon as user kills activity, foreground service also gets killed.



I read some other answers regarding the same issues,




which state that in devices like Xaomi, Oppo, lenovo, LG, honor etc.
You need to enable "AutoRun" permission for the app




Which I tried with no success. I also tried the following with no success at all:




  1. Disabled MIUI optimization

  2. Disabled Power saving

  3. Removed Battery restrictions for the app

  4. Freed the memory (Total: 3GB, Available:
    2GB)





What worked for me was enabling the: "Don't keep activites" in the Developer options but in real world application you probably wouldn't ask users to enable this option since it affects user experience.



Developer options MIUI 10



By the way, I tested my app in other devices such as pixel, nexus etc(Android studio emulators) And They all worked fine. It's only my device which is causing this issue.



Download link for the app for debugging purposes: https://anonfile.com/d4k511p1bd/app-debug_apk



Source Code



File: 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);
}

}


File: 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;
}
}


File: 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 know there's a way around this by enabling "Don't keep activities" in Developing options but I genuinely don't want the user to enable this in their device, Also I would gladly accept any alternative or code improvements to make the foreground Service work in MIUI 10.



Thankyou



EDIT:



Here's the project link: https://anonfile.com/y5Rd4bp3b9/ForegroundServiceExample_zip



And this is the tutorial I was following on YouTube: https://www.youtube.com/watch?v=FbpD5RZtbCc










share|improve this question

























  • I can't see startForeground() anywhere in your service.

    – egoldx
    Jan 2 at 16:05













  • @egoldx Actually startForeground() is there in the original code, I must've accidentally removed it while uploading source code in here. But yeah It is there in the ExampleService.java

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:39














0












0








0


0






I've been messing around with android services and facing a problem while running foreground Services in MIUI 10(Testing Device: Redmi note 5 pro)



Basically Service runs as long as the user is interacting with activity but as soon as user kills activity, foreground service also gets killed.



I read some other answers regarding the same issues,




which state that in devices like Xaomi, Oppo, lenovo, LG, honor etc.
You need to enable "AutoRun" permission for the app




Which I tried with no success. I also tried the following with no success at all:




  1. Disabled MIUI optimization

  2. Disabled Power saving

  3. Removed Battery restrictions for the app

  4. Freed the memory (Total: 3GB, Available:
    2GB)





What worked for me was enabling the: "Don't keep activites" in the Developer options but in real world application you probably wouldn't ask users to enable this option since it affects user experience.



Developer options MIUI 10



By the way, I tested my app in other devices such as pixel, nexus etc(Android studio emulators) And They all worked fine. It's only my device which is causing this issue.



Download link for the app for debugging purposes: https://anonfile.com/d4k511p1bd/app-debug_apk



Source Code



File: 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);
}

}


File: 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;
}
}


File: 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 know there's a way around this by enabling "Don't keep activities" in Developing options but I genuinely don't want the user to enable this in their device, Also I would gladly accept any alternative or code improvements to make the foreground Service work in MIUI 10.



Thankyou



EDIT:



Here's the project link: https://anonfile.com/y5Rd4bp3b9/ForegroundServiceExample_zip



And this is the tutorial I was following on YouTube: https://www.youtube.com/watch?v=FbpD5RZtbCc










share|improve this question
















I've been messing around with android services and facing a problem while running foreground Services in MIUI 10(Testing Device: Redmi note 5 pro)



Basically Service runs as long as the user is interacting with activity but as soon as user kills activity, foreground service also gets killed.



I read some other answers regarding the same issues,




which state that in devices like Xaomi, Oppo, lenovo, LG, honor etc.
You need to enable "AutoRun" permission for the app




Which I tried with no success. I also tried the following with no success at all:




  1. Disabled MIUI optimization

  2. Disabled Power saving

  3. Removed Battery restrictions for the app

  4. Freed the memory (Total: 3GB, Available:
    2GB)





What worked for me was enabling the: "Don't keep activites" in the Developer options but in real world application you probably wouldn't ask users to enable this option since it affects user experience.



Developer options MIUI 10



By the way, I tested my app in other devices such as pixel, nexus etc(Android studio emulators) And They all worked fine. It's only my device which is causing this issue.



Download link for the app for debugging purposes: https://anonfile.com/d4k511p1bd/app-debug_apk



Source Code



File: 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);
}

}


File: 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;
}
}


File: 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 know there's a way around this by enabling "Don't keep activities" in Developing options but I genuinely don't want the user to enable this in their device, Also I would gladly accept any alternative or code improvements to make the foreground Service work in MIUI 10.



Thankyou



EDIT:



Here's the project link: https://anonfile.com/y5Rd4bp3b9/ForegroundServiceExample_zip



And this is the tutorial I was following on YouTube: https://www.youtube.com/watch?v=FbpD5RZtbCc







java android dalvik






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 5:51







Ramanpreet Singh Khokhar

















asked Jan 2 at 15:57









Ramanpreet Singh KhokharRamanpreet Singh Khokhar

11




11













  • I can't see startForeground() anywhere in your service.

    – egoldx
    Jan 2 at 16:05













  • @egoldx Actually startForeground() is there in the original code, I must've accidentally removed it while uploading source code in here. But yeah It is there in the ExampleService.java

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:39



















  • I can't see startForeground() anywhere in your service.

    – egoldx
    Jan 2 at 16:05













  • @egoldx Actually startForeground() is there in the original code, I must've accidentally removed it while uploading source code in here. But yeah It is there in the ExampleService.java

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:39

















I can't see startForeground() anywhere in your service.

– egoldx
Jan 2 at 16:05







I can't see startForeground() anywhere in your service.

– egoldx
Jan 2 at 16:05















@egoldx Actually startForeground() is there in the original code, I must've accidentally removed it while uploading source code in here. But yeah It is there in the ExampleService.java

– Ramanpreet Singh Khokhar
Jan 3 at 5:39





@egoldx Actually startForeground() is there in the original code, I must've accidentally removed it while uploading source code in here. But yeah It is there in the ExampleService.java

– Ramanpreet Singh Khokhar
Jan 3 at 5:39












1 Answer
1






active

oldest

votes


















0














Maybe you should try to call Service#startForeground at the begining of your service creation in the onCreate/onStartIntent



See this post Context.startForegroundService() did not then call Service.startForeground() for more information.






share|improve this answer
























  • Thanks for the quick answer, but actually "startForeground()" is there in the original code I just messed up my source code in here and now I fixed the source code.

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:36











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54009355%2fhow-to-make-foreground-services-work-in-miui%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Maybe you should try to call Service#startForeground at the begining of your service creation in the onCreate/onStartIntent



See this post Context.startForegroundService() did not then call Service.startForeground() for more information.






share|improve this answer
























  • Thanks for the quick answer, but actually "startForeground()" is there in the original code I just messed up my source code in here and now I fixed the source code.

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:36
















0














Maybe you should try to call Service#startForeground at the begining of your service creation in the onCreate/onStartIntent



See this post Context.startForegroundService() did not then call Service.startForeground() for more information.






share|improve this answer
























  • Thanks for the quick answer, but actually "startForeground()" is there in the original code I just messed up my source code in here and now I fixed the source code.

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:36














0












0








0







Maybe you should try to call Service#startForeground at the begining of your service creation in the onCreate/onStartIntent



See this post Context.startForegroundService() did not then call Service.startForeground() for more information.






share|improve this answer













Maybe you should try to call Service#startForeground at the begining of your service creation in the onCreate/onStartIntent



See this post Context.startForegroundService() did not then call Service.startForeground() for more information.







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 2 at 16:06









Quentin KleinQuentin Klein

743622




743622













  • Thanks for the quick answer, but actually "startForeground()" is there in the original code I just messed up my source code in here and now I fixed the source code.

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:36



















  • Thanks for the quick answer, but actually "startForeground()" is there in the original code I just messed up my source code in here and now I fixed the source code.

    – Ramanpreet Singh Khokhar
    Jan 3 at 5:36

















Thanks for the quick answer, but actually "startForeground()" is there in the original code I just messed up my source code in here and now I fixed the source code.

– Ramanpreet Singh Khokhar
Jan 3 at 5:36





Thanks for the quick answer, but actually "startForeground()" is there in the original code I just messed up my source code in here and now I fixed the source code.

– Ramanpreet Singh Khokhar
Jan 3 at 5:36




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54009355%2fhow-to-make-foreground-services-work-in-miui%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

MongoDB - Not Authorized To Execute Command

in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

How to fix TextFormField cause rebuild widget in Flutter