Android AlarmManager 用于定期传感器读取

4

我有一个任务,需要周期性地在后端读取手机传感器(例如WiFi、加速度计)。

我目前的解决方案是使用AlarmManager。

具体而言,我们有:

在“主”程序中(一个活动),我们使用PendingIntent.getService:

public class Main extends Activity {
...
Intent intent = new Intent(this, AutoLogging.class);
mAlarmSender = PendingIntent.getService(this, 0, intent, 0);
am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC, 0, 5*1000, mAlarmSender);
}

在“AutoLogging”程序中(一个服务),我们定期响应闹钟:

public class AutoLogging extends Service {
...
@Override
public void onCreate() {
   Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
}
@Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show(); }
@Override public boolean onUnbind(Intent intent) { Toast.makeText(this, "onUnbind", Toast.LENGTH_SHORT).show() return super.onUnbind(intent); }
@Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show(); // 在这里读取传感器数据 }
@Override public IBinder onBind(Intent intent) { Toast.makeText(this, "onBind", Toast.LENGTH_SHORT).show(); return null; } }

我的问题是:

当我使用这个alarm service时,每次闹钟只会调用OnCreate和OnStart。

我的问题是:

(1) 我需要调用OnDestroy(或onBind、onUnbind)吗?

(2) 与“广播接收器”相比,这种使用AlarmManager的方式是否正确?

谢谢! Vincent

3个回答

0

0

AlarmManager只是使用挂起意图并执行意图操作,即在您的情况下启动服务。在闹钟到期时,将使用onCreate(如果尚未运行)创建服务,然后通过调用onStart启动服务。读取传感器数据后,可以使用stopSelf()停止服务,这最终将调用onDestroy()。您不应该在服务中显式调用onDestroy(),onBind()或onUnBind()。

如果您使用广播接收器与闹钟管理器,则必须在接收器的onReceive中启动此服务。在这种情况下,使用Service似乎是合适的。


那么,在完成传感器数据读取后,我应该在“onStart”中调用“stopSelf”吗? - user523597
顺便问一下,我当前的PendingIntent.getService和“广播接收器”有什么区别?非常感谢! - user523597
广播接收器的onReceive方法不应该执行需要较长时间的操作。如果读取传感器数据需要很长时间,则应使用服务来执行该操作。请参考https://dev59.com/0nA75IYBdhLWcg3wxcDV。 - Suresh

0

请不要将纯网址作为答案发布。它们可能在未来失效。 - mate00
没错,我只是想给回答问题的原始人员以荣誉。 - MitchHS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接