gpt4 book ai didi

android - 如何使用警报管理器重复我的服务?

转载 作者:行者123 更新时间:2023-11-29 00:30:01 25 4
gpt4 key购买 nike

我做了一个基于位置的应用程序。现在我需要每 30 分钟运行一次定位服务。为此,我尝试使用警报管理器,但它只运行一次我的服务。我需要它每 30 分钟运行一次吗?

我的代码:

gps_back_process.java:

public class gps_back_process extends Service
{
private static final String TAG = "MyService";
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("Testing", "Service got created");
Toast.makeText(this, "gps_back_process,onCreate();", Toast.LENGTH_LONG).show();
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}


@Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),gps.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "gps_back_process.onCreate();", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}

全局定位系统.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

{
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
cur_cal.add(Calendar.SECOND, 90);
Log.d("Testing", "Calender Set time:" + cur_cal.getTime());
Intent intent = new Intent(gps.this, gps_back_process.class);
Log.d("Testing", "Intent created");
PendingIntent pi = PendingIntent.getService(gps.this, 0, intent, 0);
AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm_manager.set(AlarmManager.RTC, cur_cal.getTimeInMillis(), pi);
Log.d("Testing", "alarm manager set");
Toast.makeText(this, "gps_back_process.onCreate()",
Toast.LENGTH_LONG).show();
}

最佳答案

您需要在 AlarmManager 引用上调用方法 setRepeating() 而不是 set() 方法。

    AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC, cur_cal.getTimeInMillis(), 180000, pi);

关于android - 如何使用警报管理器重复我的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16352048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com