2

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

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

4

1 回答 1

3

创建一个广播接收器,它将在接收到来自以下的广播后启动您的服务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 。

于 2013-10-27T10:25:33.220 回答