用AlarmManager写了定时发送位置,存到了数据库。发现应用程序退到后台,过一分钟后,就不再发送位置了(因为我现在写的是10s发一次,可以看到大概一分钟后就不再发送位置)。并且再次打开应用,也不发送。
本人安卓小白,因项目需要做app,app里全写的webview,没系统的学过安卓,求大佬指点。
用的小米6 和华为手机测试,测试结果一样
以下是MyService类
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
try {
startLocation(MyService.this);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int anhour=10*1000;
//任务首次执行时间
long triggerAtMillis = SystemClock.elapsedRealtime()+anhour;
Intent alarmIntent = new Intent(this,MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtMillis, pendingIntent);
} else {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtMillis, pendingIntent);
}
return super.onStartCommand(intent, flags, startId);
}
在MainActivity调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//省略
/**
* 定时发送定位
*/
Intent i = new Intent(this, MyService.class);
startService(i);