java - 如何修复位置在某些手机中每秒发送一次数据?
问题描述
这不是重复的,因为我的问题有点不同。
当应用程序关闭时,我尝试每 20 分钟发送一次位置,但是当我使用时间间隔时,它并不能很好地工作,所以我尝试使用Handler
每 20 分钟获取一次数据。代码参考也是基于另一个我不记得的问题的答案,我只是更改了一些部分。
这个构建是基于一些答案,我正在为我的家庭作业尝试,当我尝试使用minTimeInterver
应用程序时以某种方式忽略了位置更改,这就是我使用处理程序的原因。所以整个想法是每20分钟发送一次位置。
这是活动设置:
mYourService = new MyService();
mServiceIntent = new Intent(this, mYourService.getClass());
if (!isMyServiceRunning(mYourService.getClass())) {
startService(mServiceIntent);
}
服务 :
public class MyService extends Service {
private static final String TAG = "MyServiceTTT";
public int counter = 0;
private LocationManager mLocationManager = null;
private static int LOCATION_INTERVAL = 900000;
private static ApiClient mApi;
private AppDatabase appDatabase;
private static final float LOCATION_DISTANCE = 10f;
private ArrayList<Map> maps;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location.getLongitude() + " - " + location.getLatitude());
String status = AppPref.getInstance().getUserStatus();
if (AppPref.getInstance().getShiftService()) {
switch (status) {
case "true":
Log.e(TAG, "1");
TimeZone timeZone = TimeZone.getTimeZone("Asia/Tehran");
Calendar cal = Calendar.getInstance(timeZone);
cal.add(Calendar.DATE, 0);
SimpleDateFormat format1 = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
String formatted = format1.format(cal.getTime());
String star = AppPref.getInstance().getUserStartAt();
String en = AppPref.getInstance().getUserEndAt();
try {
Log.e(TAG, "2");
if (TimeConditioner.isTimeBetweenTwoTime(star, en, formatted)) {
Log.e(TAG, "3");
OnlineCordinateRequest onlineCordinateRequest = new OnlineCordinateRequest();
onlineCordinateRequest.user_id = Integer.parseInt(AppPref.getInstance().getUserID());
onlineCordinateRequest.lat = location.getLatitude();
onlineCordinateRequest.lng = location.getLongitude();
onlineCordinateRequest.methodz = "online";
onlineCordinateRequest.status = "none";
getApi().cordinate(onlineCordinateRequest).enqueue(new Callback<GeneralCallBack>() {
@Override
public void onResponse(Call<GeneralCallBack> call, Response<GeneralCallBack> response) {
Log.i(TAG, "Done");
}
@Override
public void onFailure(Call<GeneralCallBack> call, Throwable t) {
Log.i(TAG, "Failed");
createMap(Integer.parseInt(AppPref.getInstance().getUserID()), location.getLatitude(), location.getLongitude());
}
});
} else {
Log.i(TAG, "Failed");
Log.e(TAG, "4");
}
} catch (ParseException e) {
Log.i(TAG, "Failed");
Log.e(TAG, "5");
}
break;
case "false":
Log.i(TAG, "Que False");
Log.e(TAG, "6");
break;
default:
Log.i(TAG, "Que Default");
Log.e(TAG, "7");
}
} else {
Log.e(TAG, "8");
OnlineCordinateRequest onlineCordinateRequest = new OnlineCordinateRequest();
onlineCordinateRequest.user_id = Integer.parseInt(AppPref.getInstance().getUserID());
onlineCordinateRequest.lat = location.getLatitude();
onlineCordinateRequest.lng = location.getLongitude();
onlineCordinateRequest.methodz = "online";
onlineCordinateRequest.status = "none";
getApi().cordinate(onlineCordinateRequest).enqueue(new Callback<GeneralCallBack>() {
@Override
public void onResponse(Call<GeneralCallBack> call, Response<GeneralCallBack> response) {
Log.i(TAG, "Done");
Log.e(TAG, "9");
}
@Override
public void onFailure(Call<GeneralCallBack> call, Throwable t) {
Log.i(TAG, "Failed");
Log.e(TAG, "10");
createMap(Integer.parseInt(AppPref.getInstance().getUserID()), location.getLatitude(), location.getLongitude());
}
});
}
Log.e(TAG, "11");
mLastLocation.set(location);
}
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
private void createMap(int user_id, double lat, double lng) {
TimeZone timeZone = TimeZone.getTimeZone("Asia/Tehran");
Calendar cal = Calendar.getInstance(timeZone);
cal.add(Calendar.DATE, 0);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd k:m:s", Locale.ENGLISH);
String formatted = format1.format(cal.getTime());
new MyService.CreateMapLogAsyncTask().execute(new Map(0, user_id, lat, lng, "offline", "opened", formatted));
}
private class CreateMapLogAsyncTask extends AsyncTask<Map, Void, Void> {
@Override
protected Void doInBackground(Map... maps) {
long id = appDatabase.getMapDAO().addMap(maps[0]);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.i(TAG, "Added to DB");
}
}
public ApiClient getApi() {
if (mApi == null) {
mApi = ApiService.getClient().create(ApiClient.class);
}
return mApi;
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
Log.e("MyServiceTTT", "Testing Data111 : ");
}
// startMyOwnForeground();
else {
Log.e("MyServiceTTT", "Testing Data222 : ");
}
// startForeground(1, new Notification());
// startTimer();
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: " + LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
@RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "LOCATION_INTERVAL");
super.onStartCommand(intent, flags, startId);
appDatabase = AppDatabase.getInstance(getApplicationContext());
startTimer();
return START_STICKY;
}
MyService.LocationListener[] mLocationListeners = new MyService.LocationListener[]{
new MyService.LocationListener(LocationManager.PASSIVE_PROVIDER)
};
@Override
public void onDestroy() {
super.onDestroy();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex);
}
}
}
}
final Handler updateHandler = new Handler(Looper.getMainLooper());
public void startTimer() {
int timerTime = Integer.parseInt(AppPref.getInstance().getIntervalMiliSeconds()) * 60000;
LOCATION_INTERVAL = timerTime;
Log.i(TAG, String.valueOf(timerTime));
Runnable runnable = new Runnable() {
public void run() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
LOCATION_INTERVAL,
LOCATION_DISTANCE,
mLocationListeners[0]
);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
updateHandler.postDelayed(this, timerTime); // determines the execution interval
}
};
updateHandler.post(runnable);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
解决方案
实现 JobService 是最好的选择。您可以根据需要进行修改。有关更多信息,请访问官方网站
推荐阅读
- jquery - 复杂形式的Jquery验证复选框(至少一个用于组)
- c++ - 在不同的内存位置同时写入 std::deque 是线程安全的吗?
- sql - ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: text % unknown
- c# - 将字母打印为 char 的菱形
- android - 硬件加速为真或假时,图像和 CardView 阴影均不显示
- wordpress - 更改评论位置 WordPress
- .net - Akka.NET 中的用户监控/跟踪
- python - % 作为结果出现在列中
- ios - Swift UITableView 仅在我按下几秒钟时调用 didSelectRowAt
- jquery - .modal('dispose') 有什么作用?引导程序 4