gpt4 book ai didi

android - 如何每 1 分钟在后台向服务器发送经纬度值?

转载 作者:搜寻专家 更新时间:2023-11-01 08:49:36 24 4
gpt4 key购买 nike

我正在开发一个应用程序,因为当我点击开始按钮时,我必须每 1 分钟向服务器发送一次经纬度值,如果我点击停止按钮,它必须停止向服务器发送值。我尝试使用 runnable 它的工作但有时它不起作用。我不知道这是不是正确的过程,请给我任何解决方案

公共(public)类 MonitoringActivity 扩展 Activity {

private String lat;
private String lng;
private double latd;
private double lngd;
private Button startOrDelBtn;
//Runnable myHandlerTask;
private static Runnable mHandlerTask;
protected static final long INTERVAL = 2000*30;

protected static Handler mHandler;
private String val;
private int NOTIFICTION_ID=1;
NotificationCompat.Builder mBuilder;
private NotificationManager notificationManager;
MediaPlayer player ;
//private int flag_Out = 2;
private int flag_In = 1;
private String shedForPanicVal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
bar.setDisplayShowHomeEnabled(false);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowCustomEnabled(true);
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.action_bar_jamlocation);
setContentView(R.layout.activity_monitoring);

startOrDelBtn = (Button)findViewById(R.id.monitorId);




mHandlerTask = new Runnable()
{

@Override
public void run() {
mHandler = new Handler();
mHandler.postDelayed(mHandlerTask, INTERVAL);
String checkShValForPanic = SharedDB.getValue(MonitoringActivity.this);

if(checkShValForPanic=="2"){
// new SendDataAsync(MonitoringActivity.this,"2",latd,lngd).execute();
Log.e("Panic", "status 2");

// SharedDB.setValue(MonitoringActivity.this, "2");
new SendLatLngAsync(MonitoringActivity.this,"2",latd,lngd).execute();
}
else{
// else if(checkShValForPanic=="1"){
//new SendDataAsync(MonitoringActivity.this,"1",latd,lngd).execute();
Log.e("Non Panic", "status 1");
// SharedDB.setValue(MonitoringActivity.this, "1");
// SharedDB.startOrStopShare(MonitoringActivity.this, flag_In);
new SendLatLngAsync(MonitoringActivity.this,"1",latd,lngd).execute();
}
// }

}

};
int runFlag = SharedDB.getFlag(MonitoringActivity.this);
// if flag is not there i shared preference
if(runFlag==0){
Log.e("NEW", "ACTIVITY");
SharedDB.startOrStopShare(MonitoringActivity.this, flag_In);
mHandlerTask.run();
}
else{
Log.e("ALREADY", "EXIST ACTIVITY");
}


// Notification Initialization



}

public void stopMonitoring(View v){
v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
String startOrDeText = startOrDelBtn.getText().toString().trim();


try {
if(startOrDeText.equals("Stop")){
startOrDelBtn.setText("Start");
mHandler.removeCallbacks(mHandlerTask);
Log.e("STOPPED", "BUTTON");
// new SendDataAsync(MonitoringActivity.this,"0",latd,lngd).execute();
//SharedDB.startOrStopShare(MonitoringActivity.this, flag_Out);
SharedDB.removeFlag(MonitoringActivity.this);
SharedDB.startOrStopShare(MonitoringActivity.this,0);
SharedDB.setValue(MonitoringActivity.this, SharedDB.defaultVal);
new SendLatLngAsync(MonitoringActivity.this,"0",latd,lngd).execute();
notificationManager.cancel(NOTIFICTION_ID);
}
else if(startOrDeText.equals("Start")){
//SharedDB.startOrStopShare(MonitoringActivity.this, flag_Out);
Log.e("STARTED", "BUTTON");
startOrDelBtn.setText("Stop");
SharedDB.removeFlag(MonitoringActivity.this);
SharedDB.startOrStopShare(MonitoringActivity.this,flag_In);
SharedDB.setValue(MonitoringActivity.this, "1");
mHandlerTask.run();
notificationManager.notify(NOTIFICTION_ID,mBuilder.build());
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void panicReport(View v){

val="2";
try {
startOrDelBtn.setText("Stop");
mHandler.removeCallbacks(mHandlerTask);
SharedDB.removeFlag(MonitoringActivity.this);
SharedDB.startOrStopShare(MonitoringActivity.this,flag_In);
SharedDB.setValue(MonitoringActivity.this, "2");
mHandlerTask.run();
notificationManager.notify(NOTIFICTION_ID,mBuilder.build());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public class SendLatLngAsync extends AsyncTask<Void, Void, Void>{

private HttpPost httpPost;
private HttpGet httpGet;
private ArrayList<NameValuePair> arryPair;
private DefaultHttpClient httpClient;
private String response;
private Context mContext;
private double longitute;
private double latitute;
private String mStatus;
private String lati;
private String longi;
private String lat;
private String lng;
GPSTracker gpsTracker = new GPSTracker(MonitoringActivity.this);
double Lat = gpsTracker.getLatitude();
double Lng = gpsTracker.getLongitude();
private int responsecode;
private boolean isConnectedToInternet;
private ProgressDialog pDialog;

public SendLatLngAsync(Context context,String status,double lat,double lng){
this.mContext = context;
this.mStatus = status;
this.latitute = lat;
this.longitute = lng;

}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(MonitoringActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

isConnectedToInternet=CheckNetClass.isConnectedToInternet(MonitoringActivity.this);*/

}

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub

Log.e("Current In Async", Lat+" "+Lng);
String lat1= Double.toString(Lat);
String lng1= Double.toString(Lng);
/*GPSTracker tracker = new GPSTracker(this.mContext);
String latg = Double.toString(tracker.getLatitude());
String lang = Double.toString(tracker.getLongitude());
Log.e("FROM TRACKER", latg+" "+lang);*/
httpClient =new DefaultHttpClient();
httpPost = new HttpPost(UrlConstant.SEND_PANIC);
//httpGet = new HttpGet(UrlConstant.SEND_PANIC_FOR_GUEST);
try {
//Log.e("LATI", lati+longi);
arryPair = new ArrayList<NameValuePair>();
arryPair.add(new BasicNameValuePair("lat",lat1));
arryPair.add(new BasicNameValuePair("lng",lng1));
arryPair.add(new BasicNameValuePair("trackid","Durga"));
arryPair.add(new BasicNameValuePair("status", mStatus));
httpPost.setEntity(new UrlEncodedFormEntity(arryPair));

HttpResponse responsePOST = httpClient.execute(httpPost);
HttpEntity resEntity = responsePOST.getEntity();
response = EntityUtils.toString(resEntity, HTTP.UTF_8 );

responsecode = responsePOST.getStatusLine().getStatusCode();
Log.e("STATUS CODE", ""+responsecode);
Log.i("SomeTag",
"doInBackGround done at " + System.currentTimeMillis());
Log.e("MONITOR", response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
/*pDialog.dismiss();
if(isConnectedToInternet)
if(responsecode==200){

}
else{

GetAlertDialog.getDialog(MonitoringActivity.this, GetAlertDialog.serverdown);

}
else{

GetAlertDialog.getDialog(MonitoringActivity.this, GetAlertDialog.networkfailure);
}

//Toast.makeText(MonitoringActivity.this, "SUCCESS", 100).show(); */
}

}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this,MonitoringActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pIntent = PendingIntent.getActivity(this,0,intent,0);

mBuilder = new NotificationCompat.Builder(this).setContentTitle("TRACKING")
.setSmallIcon(R.drawable.panic)
.setAutoCancel(true)
.setSound(uri)
.setContentIntent(pIntent);


notificationManager.notify(NOTIFICTION_ID,mBuilder.build());
}

}

最佳答案

我在背景中使用 with service 解决了我的问题

private HttpPost httpPost;
private HttpGet httpGet;
private ArrayList<NameValuePair> arryPair;
private DefaultHttpClient httpClient;
private String response;
private int responsecode;
private double Lat;
private double Lng;
private double lat;
private double lng;
private int status;
//private String status;
private static Runnable mHandlerTask;
protected static final long INTERVAL = 1000*10;
protected static Handler mHandler;


public SendLatLngService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//status= intent.getStringExtra("status");
return super.onStartCommand(intent, flags, startId);


}
@Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();




mHandlerTask = new Runnable()
{

@Override
public void run() {


mHandler = new Handler();
mHandler.postDelayed(mHandlerTask, INTERVAL);
new asyncServ().execute();
}
};
mHandlerTask.run();

}

@Override
public void onStart(Intent intent, int startId) {
// Perform your long running operations here.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

}

@Override
public void onDestroy() {

mHandler.removeCallbacks(mHandlerTask);
Log.e("DESTROYED", "CALLED");
new asyncServ().execute();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
// TODO Auto-generated method stub

return super.bindService(service, conn, flags);
}

public class asyncServ extends AsyncTask<Void, Void, Void>{
public asyncServ(){
GPSTracker gpsTracker = new GPSTracker(SendLatLngService.this);
Lat = gpsTracker.getLatitude();
Lng = gpsTracker.getLongitude();
}

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub

String lat1= Double.toString(Lat);
String lng1= Double.toString(Lng);
httpClient =new DefaultHttpClient();
httpPost = new HttpPost(UrlConstant.SEND_PANIC);
Log.e("Status", status+"");
try {
//Log.e("LATI", lati+longi);
arryPair = new ArrayList<NameValuePair>();
arryPair.add(new BasicNameValuePair("lat",lat1));
arryPair.add(new BasicNameValuePair("lng",lng1));

httpPost.setEntity(new UrlEncodedFormEntity(arryPair));

HttpResponse responsePOST = httpClient.execute(httpPost);
HttpEntity resEntity = responsePOST.getEntity();
response = EntityUtils.toString(resEntity, HTTP.UTF_8 );


Log.i("SomeTag",
"doInBackGround done at " + System.currentTimeMillis());
// Log.e("MONITOR", response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);

}

You can call startService(intent) if you want to start service and i you want to stop then you
call stopService(intent) from your activity you must add service name in the manifest file

关于android - 如何每 1 分钟在后台向服务器发送经纬度值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837355/

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