0

I am newbie to android studio and learning about services, I visited this page : https://xjaphx.wordpress.com/2012/07/07/create-a-service-that-does-a-schedule-task/ In which author made a background service as follows: files go like:

So I create my own service called TimeService:

public class TimeService extends Service {
    // constant
    public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds

    // run on another Thread to avoid crash
    private Handler mHandler = new Handler();
    // timer handling
    private Timer mTimer = null;

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

    @Override
    public void onCreate() {
        // cancel if already existed
        if(mTimer != null) {
            mTimer.cancel();
        } else {
            // recreate new
            mTimer = new Timer();
        }
        // schedule task
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
    }

    class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    // display toast
                    Toast.makeText(getApplicationContext(), getDateTime(),
                            Toast.LENGTH_SHORT).show();
                }

            });
        }

        private String getDateTime() {
            // get date time in custom format
            SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
            return sdf.format(new Date());
        }

    }

Andoid Manfest.xml

<?xml version="1.0" encoding="utf-8"?>

<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">
    <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=".TimeService"
        android:enabled="true"
        android:exported="true"></service>
</application>

MainActivity.java is :

    package com.example.shubhamrajput.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, TimeService.class));
    }

} I tested this app on my phone ,but it is not working in the background when I terminate it from app tray, I want to make it run forever until user stops it forcefully from settings, How do I change this code? Please provide detailed explanation and also provide modified code ,so that I can understand it.How can I make it a foreground service?

iDeveloper
  • 1,699
  • 22
  • 47
user8517664
  • 1
  • 1
  • 3
  • 1
    Please understand that users have said **very loudly** that they want long battery life. Services like yours are a prime reason why battery life has been poor. This is why Android 6.0 introduced Doze mode and why Android 8.0+ limits services like yours to run for ~1 minute. I strongly encourage you to write some other app. "How can I make it a foreground service?" -- call `startForeground()` from inside the service. – CommonsWare Aug 27 '17 at 11:17
  • I know ,but can't it be done efficiently? as Gmail in phone always run in background and gives us latest updates / messages instantly ,that do not causes battery drainage? – user8517664 Aug 28 '17 at 02:56
  • "but can't it be done efficiently?" -- polling every 10 seconds? No. "as Gmail in phone always run in background" -- no, it does not. "and gives us latest updates / messages instantly" -- that is because Google is using push messaging, the sort of thing that ordinary developers get from services like Firebase Cloud Messaging. – CommonsWare Aug 28 '17 at 11:11

2 Answers2

1

You should not be running service in the background always because of it will use CPU and memory all the time.You will end up having very poor battery backup

You can use Job Scheduler for API level greater than 21 or Firebase Job Dispatcher for below API level 21.Using this, you can fire recurring job in an efficient manner.

Farmaan Elahi
  • 1,620
  • 16
  • 18
0

You can run the service on different process so it will run always irrespective of the application

In manifest file

<service
   android:name=".TimeService"
  android:enabled="true"
  android:process=":my_process">
</service> 

You can also use START_STICKY or you can follow this Answer for more details.

Sahil
  • 1,399
  • 9
  • 11
  • it closes when I exit the app – user8517664 Aug 27 '17 at 09:51
  • I have a alarm service will post it's code....if it helps? okay ? do check the edit in my amswer. What exactly is your service doing? – Sahil Aug 27 '17 at 10:08
  • I think it will be of no use. I actually used a broadcastReciever for the alarm but you need a service, What actually do you need your service to do? – Sahil Aug 28 '17 at 07:24