服务timertask自动停止android

时间:2015-05-14 23:14:43

标签: android service timer alarmmanager timertask

我在后台运行服务,定期进行各种时间间隔,间隔为10分钟。

该服务正常工作,直到应用程序处于前台并且应用程序被杀死的那一刻,时间任务表现奇怪,例如每10分钟没有被调用。

我看到它是常见的问题而且我经历了许多答案,但似乎没有什么对我有用。这是我的代码片段。请指导我错误的地方......

public class myService extends Service
{
@Override public void onCreate()
{
    super.onCreate();
    myServiceRunningBackground();
    service = myService.this;
    Log.d(TAG, "myServiceMain");
    myServiceRunningBackground();
    Message msgObj = serviceHandler.obtainMessage();
    serviceHandler.sendMessage(msgObj);
    running = true;
}

public final  Handler serviceHandler = new Handler()
{
    public void handleMessage(Message msg)
    {
        if(null != serviceTimer)
        {
            serviceTimer.cancel();
            serviceTimer.purge();
            serviceTimer = null;
        }
        serviceTimer = new Timer();

        serviceTimer.scheduleAtFixedRate(new myServiceMonitorPower(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);
        serviceTimer.scheduleAtFixedRate(new myServiceMonitorLocation(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);

       /* if(target.equals(Target.SERVER))
        {*/
        serviceTimer.scheduleAtFixedRate(new myServiceMonitorTrafficStats(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);
        // }

    }
};
@Override public int onStartCommand(Intent intent, int flags, int startId)
{
    if(intent != null)
    {      
        setTimerInfo(intent.getStringExtra("Current"));
        Message msgObj = serviceHandler.obtainMessage();
        serviceHandler.sendMessage(msgObj);
    }
    return START_STICKY;
}
@Override public IBinder onBind(Intent intent)
{
    return null;
}
@Override public boolean onUnbind(Intent intent)
{
    return super.onUnbind(intent);
}
@Override public void onRebind(Intent intent)
{
    super.onRebind(intent);
}
@Override public void onDestroy()
{
    super.onDestroy();
    running = false;
}

private void setTimerInfo(String check)
{
    if(check != null)
    {
        Log.d(TAG, "Check "+ check);
        if (check.equals("enable"))
        {
        //    alarm.SetAlarm(service, 5000);
            target = Target.DEVICE;
            DELAY_TIMER_TIME = 0;
            TIMER_START_TIME = 5000;
        }
        if (check.equals("disable"))
        {
         //   alarm.SetAlarm(service, 600000);
            myServiceRunningBackground();
            target = Target.SERVER;
            DELAY_TIMER_TIME = 300000;
            TIMER_START_TIME = 600000;
        }
    }
}

private void myServiceRunningBackground()
{
    Log.d(TAG,"esServcie  ");
    final int restartAlarmInterval = 600000;
    final int resetAlarmTimer = 2*30*1000;
    final Intent restartIntent = new Intent(this, myService.class);
    restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
    final AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Handler restartServiceHandler = new Handler()
    {
        @Override public void handleMessage(Message msg)
        {
            PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
          //  alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
            alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pintent);
            sendEmptyMessageDelayed(0, resetAlarmTimer);
        }
    };
    restartServiceHandler.sendEmptyMessageDelayed(0, 0);

}

public enum Target
{
    SERVER,
    DEVICE
}
private static boolean running;
public Timer serviceTimer;
private static myService service; 

static Target target = null;

public  int DELAY_TIMER_TIME = 60000;
public  int TIMER_START_TIME = 600000;
private static final String TAG = "myService";

} 所以我也使用了警报管理器,但似乎它不起作用。我希望当应用程序处于具有10分钟周期的后台时,所有三个timertask都应该保持运行。

要启动服务模式并将服务模式从5秒改为10分钟,请使用以下活动代码

  private void startServices() {
    Log.d(TAG, "StartServices ");
    Intent intent = new Intent(myActivity.this, myService.class);
    intent.putExtra("Current", "enable"); //disable for 10 mins on onDestroy 
    startService(intent);
}

感谢您的任何建议

3 个答案:

答案 0 :(得分:0)

您需要针对不同的时间表初始化三个Timer。从这个片段:

serviceTimer = new Timer();
serviceTimer.scheduleAtFixedRate(new myServiceMonitorPower(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);
serviceTimer.scheduleAtFixedRate(new myServiceMonitorLocation(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);
serviceTimer.scheduleAtFixedRate(new myServiceMonitorTrafficStats(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);

我们可以知道serviceTimer完全令人困惑,TimerTask将被安排。所以解决方法是,确保初始化3 Timer s:

serviceTimer = new Timer();
timer2 = new Timer();
timer3 = new Timer();

serviceTimer.scheduleAtFixedRate(new myServiceMonitorPower(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);
timer2.scheduleAtFixedRate(new myServiceMonitorLocation(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);
timer3.scheduleAtFixedRate(new myServiceMonitorTrafficStats(service, target), DELAY_TIMER_TIME, TIMER_START_TIME);

并在Service被摧毁后取消它们:

@Override
public void onDestroy(){
    running = false;
    serviceTimer.cancel();
    timer2.cancel();
    timer3.cancel();
    super.onDestroy();
}

使用AlarmManager短时间任务可能会耗尽用户的电量,请改用Timer

答案 1 :(得分:0)

编辑:这并不是一项服务。但是,如果其他人希望代码在预定时间运行而不是作为服务运行,那么这将起作用

整体申请类:

public class ExampleApp extends Application {
    private SharedPreferences sharedPref;
    @Override
    public void onCreate() {
        super.onCreate();
        sharedPref = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    }
    private AlarmReceiver alarmReceiver;
    private void setAlarm(Long duration) {
        sharedPref.edit().putBoolean("alarmSet",true).apply();
        alarmReceiver = new AlarmReceiver();
        alarmReceiver.setTimer(this, duration);
    }

    public void cancelAlarm() {
        sharedPref.edit().putBoolean("alarmSet",false).apply();
        alarmReceiver.cancelTimer(this);
    }
}

AlarmReceiverClass

public class AlarmReceiver extends BroadcastReceiver {
    private PendingIntent pendingIntent;
    private AlarmManager alarmManager;
    private Intent intent;

    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        sharedPref.edit().putBoolean("alarmSet",false).apply();
        //TODO: DO YOUR STUFF HERE
    }

    public void setTimer(Context context, Long addition) {
        alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        intent = new Intent(context, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + addition, pendingIntent);
}

    public void cancelTimer(Context context) {
        alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        intent = new Intent(context, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        alarmManager.cancel(pendingIntent);
    }
}

从以下任何活动开始:

((ExampleApp)getApplication()).setAlarm(10000);

答案 2 :(得分:0)

请看!!!

1.首先,您应该在应用程序文件中保存服务实例
2.你可以在几秒后使用闹钟,如果实例是现场,则无需启动服务,否则你需要再次启动服务

对你有帮助