【问题标题】:Service that repeatedly runs a method, after an amount of time在一段时间后重复运行方法的服务
【发布时间】:2015-05-28 21:37:16
【问题描述】:

我想创建一个服务,它会在 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); 
}

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

【问题讨论】:

    标签: java android service timer alarmmanager


    【解决方案1】:

    创建一个广播接收器,它将在接收到来自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

    【讨论】:

    • 谢谢。我今天下午去试试。
    • 我不太懂代码。如果你能告诉我我必须把女巫代码放在哪里,我认为这对我很有帮助。
    • SyncAlaram 是可重用的类。只需将其添加到您的项目中。在MainActivity 中添加第二个代码块,在清单文件中添加最后一个代码块。这是一个很好的教程vogella.com/articles/AndroidServices/article.html,它可以让你开始使用服务,以防你没有得到任何这些。 :)
    • 这个可以帮助您开始使用广播接收器:vogella.com/articles/AndroidBroadcastReceiver/article.html
    • 非常感谢。我希望我能得到它
    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 2011-09-28
    • 2014-10-16
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多