经过一段时间后重复运行方法的服务

时间:2013-10-27 10:14:18

标签: java android service timer alarmmanager

我想创建一个服务,一次又一次地在10秒后运行一个方法,直到我停止它,即使该应用程序已关闭。我的尝试代码在

之下
package com.example.tauben;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class Reminder extends Service {


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

    @Override
    public void onCreate() {
        TimerTask task = new TimerTask() {
            public void run(){
                f();
            }
        };

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, 0, 10000);
    }

    public void f(){
        Toast t = Toast.makeText(this, "Service is still running", Toast.LENGTH_SHORT);
        t.show();
   }

}

这就是我开始服务的方式。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(Log_TAG,"_____________RESTART__________");

    Intent i= new Intent(this, Reminder.class);
    startService(i); 
}

程序立即停止运行;如何更改代码以获得所需的行为?

1 个答案:

答案 0 :(得分:4)

创建一个广播接收器,在接收到来自AlarmManager的广播后启动您的服务:

public class SyncAlarm extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent data) {

    // set alarm to start service
    Calendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(System.currentTimeMillis());

    Calendar cal = new GregorianCalendar();
    cal.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR));
    cal.set(Calendar.HOUR_OF_DAY,  calendar.get(Calendar.HOUR_OF_DAY));

    // start service after an hour
    cal.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 60);
    cal.set(Calendar.SECOND, calendar.get(Calendar.SECOND));
    cal.set(Calendar.MILLISECOND, calendar.get(Calendar.MILLISECOND));
    cal.set(Calendar.DATE, calendar.get(Calendar.DATE));
    cal.set(Calendar.MONTH, calendar.get(Calendar.MONTH));

    // set alarm to start service again after receiving broadcast
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, SyncAlarm.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    am.cancel(pendingIntent);
    am.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);

    intent = new Intent(context, Reminder.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startService(intent);
    }
}

启动应用程序时第一次启动广播接收器:

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, SyncAlarm.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    am.cancel(pendingIntent);
    am.set(AlarmManager.RTC, System.currentTimeMillis(), pendingIntent);

还要将此添加到您的清单文件:

<receiver android:name=".SyncAlarm" >
</receiver>

如果您希望在资源可用时立即由Android系统启动您的服务,而不是通过AlarmManager接收广播,那么您也应该参与此START_STICKY