1

I want to re-start my IntentService (which handles HTTP POST request) every 10 seconds. I tried using AlarmManager and PendingIntent as descrribed in every posts. But my IntentService doesn't starts. I'm unable to find any reason for this so any help would be appreciated.

IntentService

public class MyService extends IntentService{

    public MyService() {
        super("MyService");
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
      System.out.println("Service Started");
        // POST request code here
    }
}

MainActivity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start();
    }

    public void start() {
         Intent intent = new Intent(this, MyService.class);
            intent.putExtra("com.hybris.proxi.triggerTime", 5000);
            PendingIntent pendingIntent = PendingIntent.getService(this,  0,  intent, 0);
            long trigger = System.currentTimeMillis() + (5*1000);
            AlarmManager am =( AlarmManager)getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, trigger, pendingIntent);
    }
}
Somnath Pal
  • 190
  • 1
  • 15

1 Answers1

1

You can use this code:

 final Handler handler = new Handler();

        TimerTask timertask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        startService(new Intent(getApplicationContext(),
                                MyService.class));
                    }
                });
            }
        };
        Timer timer = new Timer();
        timer.schedule(timertask, 0, 10000);
        }

This will execute at an interval of 10 seconds

Also,add your Service class to manifest:

       <service
            android:name=".MyService"
            android:enabled="true" >
        </service>
Jas
  • 3,207
  • 2
  • 15
  • 45