pawan kalyan
pawan kalyan

Reputation: 23

how to run background service forever in android

I am trying to change the wallpaper according to the time set by the user, it is working fine for any long time when I run it on the emulator and also on mobile by connecting it through USB. But when I generated Signed apk and installing on it the same mobile it is not working, the app is terminating after some while.

Can anyone help me, please?

This is my manifest file:

<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".WllPaper" />
    <service android:name=".MyThreadOne"
        android:enabled="true"/>
    <receiver android:name=".SensorRestarterBroadcastReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">

        <intent-filter>

            <action android:name="ac.in.ActivityRecongnition.RestartSensor"/>
        </intent-filter>
    </receiver>
    <service android:name=".NewThreadClass"/>
    <activity android:name=".NewWallpaper"/>


    <meta-data
        android:name="preloaded_fonts"
        android:resource="@array/preloaded_fonts" />
</application>

Upvotes: 1

Views: 5247

Answers (3)

Richard Dapice
Richard Dapice

Reputation: 885

First, there is no guarantee that work will continue in the background on Android anymore. Different OEM's treat background work differently see here for a list. https://dontkillmyapp.com/ Some googling will show you what is possible with Android as of right now. Just expect that NOTHING will behave exactly how you would like it to. I have had the most success with WorkManager.

You could use JobScheduler or AlarmManager perhaps to achieve your desired results. But what you should be using is WorkManager an abstraction of both depending on Android version.

WorkManager is highly configurable and will allow you to create a PeriodicWorkRequest or a OneTimeWorkRequest these are guaranteed to succeed. PeriodicWorkRequest will fire when you schedule the work, as well as when you have specified in the timer. It will execute in the background even if the app is closed or backgrounded. If you didn't want your task to execute immediately you can use a PWR(PeriodicWorkRequest) with a FlexInterval. See the docs below for more info.

WorkManager Docs

WorkManager Architecture

WorkmManager CodeLab

For example, I created two PeriodicWorkRequests that refresh services and keeps the user logged in always by renewing their token. When the user authenticates the PeriodicWorkRequest is created. In my case, I didn't need it to fire right away as they have just received and cached this information so I utilized the FlexInterval. When the app is backgrounded or closed, the workers continue to refresh services every 12 hours and refresh the token every 6. It works like a charm.

Here is an example:

Build Work:

 override fun beginWork() {

        val periodicWorkRequest = PeriodicWorkRequest.Builder(
                MyWorker::class.java,
                REPEAT_INTERVAL, TimeUnit.MINUTES, // How often work should repeat
                // Flex not required.
                FLEX_INTERVAL, TimeUnit.MINUTES) // Limits execution into a time window
                .setConstraints(
                     Constraints.Builder().setRequiredNetworkType(
                                       NetworkType.CONNECTED).build())
                .addTag(MY_WORKER_TAG)
                .build()

        WorkManager.getInstance().enqueueUniquePeriodicWork(
                MY_UNIQUE_WORK,
                ExistingPeriodicWorkPolicy.KEEP,
                periodicLoginRequest)

Worker:

class MyWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): Result {
            // DO WORK HERE

            Result.success()
        } else {
            // HANDLE FAILURE HERE
            Result.failure()
        }

The above is a simple implementation, but it should give you the general idea.

Upvotes: 4

Lokesh Kedia
Lokesh Kedia

Reputation: 11

Try implimanting job service class ,which will run for lifetime in background

Upvotes: 0

Alex Hart
Alex Hart

Reputation: 1703

Android no longer allows arbitrary background services. You need to mark it as a foreground service in your manifest.

https://developer.android.com/guide/components/services

Alternatively, you might be able to use AlarmManager to build this behavior.

https://developer.android.com/reference/android/app/AlarmManager

Upvotes: 0

Related Questions