sS3tYo
sS3tYo

Reputation: 21

Android service keeps stopping - "Background execution not allowed: receiving Intent"

I have a location service that runs when user clicks a button and applies th location.

However, it gets killed after about a minute. I've tested it on android 8/9. I've read some other answers on here about it but they haven't helped, but my knowledge on intents and broadcasts isn't good.

LocationService.java

public class LocationService extends Service {

    MockLocationProvider mockNetwork;
    MockLocationProvider mockGps;

    private static final int NOTIFICATION = 1;
    static NotificationManager notificationManager;

    Context context;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful

        context = getApplicationContext();

        pushLocation(intent);

        return LocationService.START_STICKY;
    }

    @Override
    public void onDestroy() {
        shutdown();

        super.onDestroy();
    }

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

    private void pushLocation(Intent intent) {
        try {
            if (intent.hasExtra("lat") && intent.hasExtra("lng") ) {
                double lat = intent.getDoubleExtra("lat", 45);
                double lng = intent.getDoubleExtra("lng", 45);

                mockNetwork = new MockLocationProvider(LocationManager.NETWORK_PROVIDER, context);
                mockGps = new MockLocationProvider(LocationManager.GPS_PROVIDER, context);

                mockNetwork.pushLocation(lat, lng);
                mockGps.pushLocation(lat, lng);

                setNotification(lat, lng);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setNotification(Double mLat, Double mLng) {
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
            notificationManager.createNotificationChannel(notificationChannel);
            builder = new NotificationCompat.Builder(context, notificationChannel.getId());

        } else {
            builder = new NotificationCompat.Builder(context);
        }

        //open MainActivity when clicked
        pendingIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP),
                0);

        //action when notification button clicked
        Intent intentAction = new Intent(context, ActionReceiver.class);
        intentAction.putExtra("action","actionNotification");
        pendingCloseIntent = PendingIntent.getBroadcast(context,0, intentAction, PendingIntent.FLAG_UPDATE_CURRENT);

        //build notification
        builder = builder
                .setSmallIcon(R.drawable.ic_logo)
                .setColor(ContextCompat.getColor(context, R.color.colorPrimary))
                .setContentTitle(getString(R.string.app_name) + " is running...")
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setContentText(mLat + ", " + mLng)
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .setTicker(getString(R.string.app_name) + " is running...") //accessibility
                .addAction(android.R.drawable.ic_menu_close_clear_cancel, "STOP", pendingCloseIntent)
                .setOngoing(true);

        notificationManager.notify(NOTIFICATION, builder.build());
    }

    public void shutdown() {
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION);

        if (mockNetwork != null)
            mockNetwork.shutdown();
        if (mockGps != null)
            mockGps.shutdown();
    }
}

ActionReceiver.java

public class ActionReceiver extends BroadcastReceiver {

    Context context;

    MockLocationProvider mockNetwork;
    MockLocationProvider mockGps;

    private static final int NOTIFICATION = 1;

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getStringExtra("action");
        if(action.equals("actionNotification")){

            mockNetwork = new MockLocationProvider(LocationManager.NETWORK_PROVIDER, context);
            mockGps = new MockLocationProvider(LocationManager.GPS_PROVIDER, context);

            NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(NOTIFICATION);

            try {
                if (mockNetwork != null)
                    mockNetwork.shutdown();
                if (mockGps != null)
                    mockGps.shutdown();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

These are registered in my AndroidManifest with permissions:


...

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

<receiver android:name="com.package.locationtest.ActionReceiver" />

<service
    android:name=".LocationService"
    android:label="Service">
</service>

I don't understand the problem here. Can anyone help?

Upvotes: 1

Views: 346

Answers (2)

sS3tYo
sS3tYo

Reputation: 21

I think I've sorted it, or almost sorted it. I call the service with:

startForegroundService(intent);

Instead of:

context.startService(intent);

I added the permission:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

And modified the service as follows:

public class LocationService extends Service {

    MockLocationProvider mockNetwork;
    MockLocationProvider mockGps;

    static NotificationManager notificationManager;

    Context context;

    private static final int ID_SERVICE = 101;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        context = getApplicationContext();

        // Create the Foreground Service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_menu_pin_drop_24dp)
                .setColor(ContextCompat.getColor(context, R.color.default_error_color))
                .setContentTitle(getString(R.string.app_name) + " is running...")
                .setPriority(PRIORITY_MIN)
                .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_SERVICE, notification);
        pushLocation(intent);

        return LocationService.START_STICKY;
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(NotificationManager notificationManager){
        String channelId = "my_service_channelid";
        String channelName = "My Foreground Service";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        // omitted the LED color
        channel.setImportance(NotificationManager.IMPORTANCE_NONE);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }

    @Override
    public IBinder onBind(Intent intent) {
        pushLocation(intent);

        return null;
    }

    private void pushLocation(Intent intent) {
        try {
            if (intent.hasExtra("lat") && intent.hasExtra("lng") ) {
                double lat = intent.getDoubleExtra("lat", 45);
                double lng = intent.getDoubleExtra("lng", 45);

                mockNetwork = new MockLocationProvider(LocationManager.NETWORK_PROVIDER, context);
                mockGps = new MockLocationProvider(LocationManager.GPS_PROVIDER, context);

                mockNetwork.pushLocation(lat, lng);
                mockGps.pushLocation(lat, lng);

                //setNotification(lat, lng);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I used the example notification code here:

Android - implementing startForeground for a service?

I notice the service gets killed without warning after about 25-30 minutes, but then seems to restart itself again soon enough. Maybe something to do with the onBind method?

Does anyone know how to prevent this restarting?

EDIT: Doing some more testing the service hasn't shut down, I think it's more to do with the 'improved location' option stuff being enabled on the phone that's causing the issue!

Upvotes: 1

MarkWalczak
MarkWalczak

Reputation: 1571

You should use ForegroundService instead of Service. Call startForegroundService() when you want to start it and then in onCreate method call startForeground(). With startForeground you have to pass a notification to inform the user that service is running.

Moreover I've found that some devices like HUAWEI have a feature called “power-intensive app monitor“. It kills every app that runs in the background for a long time unless user gives special permissions to it. The path to do this: Settings -> Security & privacy -> Location services -> recent location requests: YOUR APP NAME -> Battery -> uncheck Power-intensive prompt, App launch: Manage manually: check all three positions: Auto-launch, secondary launch, run in background.

I don’t know is there a way to do this programmatically. I think the best way is to create a sort of help activity and explain the user what to do if application won’t work.

Upvotes: 0

Related Questions