一次运行android应用程序

时间:2015-10-27 14:50:19

标签: android

我是android的新手。

我使用波纹管代码在特殊时间运行应用程序。但是有时候当手机被锁定而屏幕关闭时,服务会停止并且不起作用。

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;
}
}

1 个答案:

答案 0 :(得分:1)

当设备进入睡眠状态时,您的代码将不会被调用,我建议您使用AlarmManager来处理您的代码,而不是您的服务。 然后,您可以将代码放在Receiver的onReceive方法中,如果需要,可以在代码执行之前获取唤醒锁。