Java 如何确定某些手机中每秒发送数据的位置?
这不是重复,因为我的问题是有点不同 当应用程序关闭时,我尝试每20分钟发送一次位置信息,但当我使用“时间间隔”时,它不会很好地工作,所以我尝试使用Java 如何确定某些手机中每秒发送数据的位置?,java,android,Java,Android,这不是重复,因为我的问题是有点不同 当应用程序关闭时,我尝试每20分钟发送一次位置信息,但当我使用“时间间隔”时,它不会很好地工作,所以我尝试使用处理程序每20分钟获取一次数据。代码参考也是基于另一个问题的答案,我不记得了,我只是更改了一些部分 这个构建是基于一些答案的,这是我的家庭作业,当我试图使用mintimeinterviapp时,不知何故忽略了位置的变化,这就是我使用handler的原因。因此,整个想法是每20分钟发送一次位置 以下是活动设置: mYourService = ne
处理程序
每20分钟获取一次数据。代码参考也是基于另一个问题的答案,我不记得了,我只是更改了一些部分
这个构建是基于一些答案的,这是我的家庭作业,当我试图使用mintimeintervi
app时,不知何故忽略了位置的变化,这就是我使用handler的原因。因此,整个想法是每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;
}
}
服务:
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;
}
}
公共类MyService扩展服务{
私有静态最终字符串TAG=“myservicett”;
公共整数计数器=0;
私有位置管理器mLocationManager=null;
专用静态int位置_间隔=900000;
私有静态ApiClient mApi;
私有应用数据库;
专用静态最终浮动位置_距离=10f;
私有数组列表映射;
私有类LocationListener实现android.location.LocationListener{
位置mLastLocation;
公共位置侦听器(字符串提供程序){
Log.e(标记“LocationListener”+提供者);
mLastLocation=新位置(提供商);
}
@凌驾
已更改位置上的公共无效(位置){
Log.e(标记“onLocationChanged:”+location.getLongitude()+“-”+location.getLatitude());
字符串状态=AppPref.getInstance().getUserStatus();
if(AppPref.getInstance().getShiftService()){
开关(状态){
案例“真”:
日志e(标签“1”);
时区时区=TimeZone.getTimeZone(“亚洲/德黑兰”);
Calendar cal=Calendar.getInstance(时区);
cal.add(Calendar.DATE,0);
SimpleDataFormat 1=新的SimpleDataFormat(“HH:mm:ss”,Locale.ENGLISH);
String formatted=format1.format(cal.getTime());
字符串star=AppPref.getInstance().getUserStartAt();
字符串en=AppPref.getInstance().getUserEndAt();
试一试{
日志e(标签“2”);
if(timeconditor.istimetweentwoitime(星形,en,格式化)){
日志e(标签“3”);
OnlineCordinateRequest OnlineCordinateRequest=新的OnlineCordinateRequest();
onlineCordinateRequest.user_id=Integer.parseInt(AppPref.getInstance().getUserID());
onlineCordinateRequest.lat=location.getLatitude();
onlineCordinateRequest.lng=location.getLongitude();
onlineCordinateRequest.methodz=“在线”;
onlineCordinateRequest.status=“无”;
getApi().cordinate(onlineCordinateRequest).enqueue(新回调()函数){
@凌驾
公共void onResponse(调用、响应){
Log.i(标记“完成”);
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Log.i(标记“失败”);
createMap(Integer.parseInt(AppPref.getInstance().getUserID())、location.getLatitude()、location.getLength();
}
});
}否则{
Log.i(标记“失败”);
日志e(标签“4”);
}
}捕获(解析异常){
Log.i(标记“失败”);
日志e(标签“5”);
}
打破
案例“假”:
Log.i(标记为“Que False”);
日志e(标签“6”);
打破
违约:
Log.i(标记“Que Default”);
日志e(标签“7”);
}
}否则{
日志e(标签“8”);
OnlineCordinateRequest OnlineCordinateRequest=新的OnlineCordinateRequest();
onlineCordinateRequest.user_id=Integer.parseInt(AppPref.getInstance().getUserID());
onlineCordinateRequest.lat=location.getLatitude();
onlineCordinateRequest.lng=location.getLongitude();
onlineCordinateRequest.methodz=“在线”;
onlineCordinateRequest.status=“无”;
getApi().cordinate(onlineCordinateRequest).enqueue(新回调()函数){
@凌驾
公共void onResponse(调用、响应){
Log.i(标记“完成”);
日志e(标签“9”);
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Log.i(标记“失败”);
日志e(标签“10”);
createMap(Integer.parseInt(AppPref.getInstance().getUserID())、location.getLatitude()、location.getLength();
}
});
}
日志e(标签“11”);
mLastLocation.set(位置);
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
Log.e(标记“onProviderDisabled:+pro