2

I want that the service is running even if the application is closed ( killed ) or even if the user does not start the application . I want to start the service after the application is installed and from this point , the service requires to run constantly every ten minutes.

Although I found some solutions such as

those are not working to me as I am new in Android programming. If there is any sample working source code, please provide me the information how to develop it.

Here is my Service Class..

public class MyService extends Service {

    MyReceiver receiver = new MyReceiver();

    public void onCreate()
    {
        super.onCreate();       
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        receiver.SetAlarm(this);
        return START_STICKY;
    }

    @Override        
    public void onStart(Intent intent, int startId)
    {
        receiver.SetAlarm(this);
    }

}

Here is my Receiver Class..

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
            wl.acquire();

            // Put here YOUR code.
            Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

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

    public void SetAlarm(Context context)
    {
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, UploadLocReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
    }

}

I added service and receiver in AndroidManifest.xml file.

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

<service android:name=".MyService" 
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </service>

 <receiver android:name=".MyReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

I've added below codes in my Main Activity.

Intent service = new Intent(getApplicationContext(), MyService.class);
        this.startService(service);
Community
  • 1
  • 1
NML
  • 105
  • 1
  • 11

2 Answers2

1

Android OS will notify when you install application form play store.

1. Add receiver in manifest file, which will notify you that user has installed application:

<receiver android:name="com.mypackagename.Installreceiver" android:exported="true">
      <intent-filter>
          <action android:name="com.android.vending.INSTALL_REFERRER" />
     </intent-filter>
</receiver>

2. Start service which will run continues every 10 minutes from Installreceiver broadcast receiver.

public class Installreceiver extends BroadcastReceiver{
       @Override
        public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context.getApplicationContext(), YourService.class));
       }
    }

YourService.java:

public class YourService extends Service {

    private static String TAG = "MyService";
    private Handler handler;
    private Runnable runnable;
    private final int runTime = 10000;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                handler.postDelayed(runnable, runTime);
            }
        };
        handler.post(runnable);
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
}

Update 1:

3. If OS kill your service then you need to start again by doing another receiver.

Add below two methods in service:

@Override
public void onTaskRemoved(Intent rootIntent) {
   super.onTaskRemoved(rootIntent);
   sendBroadcast(new Intent("IWillStartAuto"));
}

 @Override
 public void onDestroy() {
   super.onDestroy();
   sendBroadcast(new Intent("IWillStartAuto"));
 }

4. Add receiver in manifest.

<receiver android:name=".RestartServiceReceiver" >
     <intent-filter>
         <action android:name="IWillStartAuto" >
         </action>
      </intent-filter>
 </receiver>

5. Add receiver:

public class RestartServiceReceiver extends BroadcastReceiver{
   @Override
    public void onReceive(Context context, Intent intent) {
    context.startService(new Intent(context.getApplicationContext(), YourService.class));
   }
}

Update 2:

6. Add permission in manifest.

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

7. Add receiver in manifest.

<receiver android:name=".BootCompletedReceiver" >
      <intent-filter>
             <action android:name="android.intent.action.BOOT_COMPLETED" />
             <action android:name="android.intent.action.QUICKBOOT_POWERON" />
      </intent-filter>
</receiver>

7. BootCompletedReceiver,java:

public class BootCompletedReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent arg1) {
    context.startService(new Intent(context.getApplicationContext(), YourService.class));
  }
}

Hope this will help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • Hi @HirenPatel, I followed your code. However, it run one time when I launch the application. If I close/kill the application, service run one time. It does not run in every ten minutes. I tried to add log message in "OnStartCommand" method of MyService class. – NML Mar 31 '16 at 09:05
  • @NML, yes please share query – Hiren Patel Mar 31 '16 at 09:06
  • Hi @HirenPatel, I followed your code. However, it run one time when I launch the application. If I close/kill the application, service run one time. It does not run in every ten minutes. I tried to add log message in "OnStartCommand" method of MyService class. – NML Mar 31 '16 at 09:50
  • @NML, do you want to do some operation in Service ? if yes than you can add code in Runnable method, it will get called every ten minutes, if no than let me know i ll update answer – Hiren Patel Mar 31 '16 at 09:52
  • Thank you so much. I added the code in Runnable. It is working well now. – NML Mar 31 '16 at 10:30
  • @NML, Glad to help you. – Hiren Patel Mar 31 '16 at 10:39
  • Hi Hiren Patel, I have one more question. When I power off my device and powner on it again, the service is not starting. I tried to added in as below ` ` May I know how I should do for it? I still want to run the service without starting application. – NML Apr 01 '16 at 02:19
  • @NML, I have updated my answer with Update 2 lable, please check it – Hiren Patel Apr 01 '16 at 04:32
  • Hi Hiren Patel, I followed your code to be able to run service for reboot device. However, it is not working. – NML Apr 01 '16 at 07:11
  • @NML, can you please add log for Receiver getting called or not ? And what is target version in build.gradle file ? – Hiren Patel Apr 01 '16 at 07:14
  • I've added log for Receiver. It never goes into onReceive() method of BootCompletedReceiver class . My target sdk version is 19. My device android version is 4.4.3. – NML Apr 01 '16 at 07:18
  • @NML, did you removed boot_complete action form Installreceiver receiver in manifest ? – Hiren Patel Apr 01 '16 at 07:21
  • Yes, I did. I add boot_complete action in Installreceiver receiver. Now it is working already. Thanks a lot. – NML Apr 01 '16 at 07:43
  • @NML, Glad to help you :) – Hiren Patel Apr 01 '16 at 07:45
  • Service is running well all the time. Now the problem is that sometimes service didn't process in correct duration. How should we handle this case? – NML Apr 06 '16 at 01:29
  • `public class MyService extends Service { InstallReceiver rcv = new InstallReceiver(); //try to get duration from SQLite DB int duration = getDbKeyValue("duration")); private Handler handler; private Runnable runnable; private final int runTime = 60000 * duration ; public void onCreate() { super.onCreate(); handler = new Handler(); runnable = new Runnable() { @Override public void run() { handler.postDelayed(runnable, runTime); uploadLoc(); Intent i = new Intent(); i.setAction(".startUpload"); startService(i); } }; handler.post(runnable); } }` – NML Apr 06 '16 at 01:31
0

Well, you already have answer in your question, all you need to do is just try those answers. If you still can't make it then post your code here. That's how Stack overflow works.

FYI use AlarmManager for 10 min interval :)

Aks4125
  • 4,522
  • 4
  • 32
  • 48