mohammad
mohammad

Reputation: 241

run android application at a time

I am new in android.

I use bellow code to run application at a special time. but some times when mobile phone is locked and screen is off , service stops and does not work.

public class TimeService extends Service {
IBinder mBinder;
Timer t;
public IBinder onBind(Intent intent) {
    return mBinder;
}
public void onDestroy(){
    t.cancel();
}
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());
    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.A  LARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);
    super.onTaskRemoved(rootIntent);
}
public int onStartCommand(Intent intent, int flags, int startId) {
    final DbHelper db=new DbHelper(this);
    int time[]=db.getAlarmTime();
    Calendar c = Calendar.getInstance();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute=c.get(Calendar.MINUTE);
        int rt=(time[0]*3600+time[1]*60)-(hour*3600+minute*60)*1000;
        t=new Timer();
        t.schedule(
                new TimerTask() {
                    public void run() {
                        //codes...
                        stopService(i);
                        startService(i);
                    }
                },rt
        );
    return START_STICKY;
}
}

Upvotes: 1

Views: 42

Answers (1)

Hicham
Hicham

Reputation: 770

When the device goes to sleep state, your code will not be called, I suggest that you use AlarmManager to handle your code, instead of your service. You can then put your code inside a Receiver's onReceive method, and if you need you can acquire a wakelock until your code is executed.

Upvotes: 1

Related Questions