我想要当前位置并在我的ASP.Net Web服务上发送该位置。 我写下面的代码。 后台服务是从使用此代码开始,但我没有获得位置。 不调用OnLocationChange()方法。 请帮助我。
以下代码:
设置闹钟代码:
@TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean AlarmSet(Context context, String function, AlarmManager alarmMan) {
AlarmManager alarmManager = alarmMan;
PendingIntent pending_intent;
DatabaseHandler DB;
try {
DB = new DatabaseHandler(context);
String state = function;
final Intent myIntent = new Intent(context, AlarmReceiver.class);
final Calendar calendar = Calendar.getInstance();
if (state.contains("setall")) {
String result = DB.ConvStrSelctTripTimeDetails();
String[] row = result.split("##@@");
for (int i = 0; i < row.length; i++) {
String[] data = row[i].split("#");
int rowid = Integer.parseInt(data[0]);
int shiftid = Integer.parseInt(data[1]);
int dayid = Integer.parseInt(data[2]);
if (dayid != 7) {
dayid = dayid + 1;
} else {
dayid = 1;
}
String[] strtIN = data[3].split(":");
String[] endIN = data[4].split(":");
String[] strtOUT = data[5].split(":");
String[] endOUT = data[6].split(":");
String alarmStartIN = "1";
//IN_Start
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strtIN[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(strtIN[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "s");
alarmStartIN = String.valueOf(rowid) + "1";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//IN_End
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endIN[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(endIN[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "e");
alarmStartIN = String.valueOf(rowid) + "2";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//OUT_Start
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strtOUT[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(strtOUT[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "s");
alarmStartIN = String.valueOf(rowid) + "3";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
//OUT_End
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endOUT[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(endOUT[1]));
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayid);
myIntent.putExtra("ShiftID", String.valueOf(shiftid));
myIntent.putExtra("ops", "e");
alarmStartIN = String.valueOf(rowid) + "4";
pending_intent = PendingIntent.getBroadcast(context, Integer.parseInt(alarmStartIN), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
common.writelog("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
Log.e("common", "AlarmSet() Alram Set ID :" + alarmStartIN);
}
return true;
} catch (Exception ex) {
common.writelog("common", "AlarmSet() Value:"+ function +": Error:361:" + ex.getMessage());
Log.e("common", "onCreate() Value:"+ function +": Error:361:" + ex.getMessage());
return false;
}
}
AlarmReceiver文件代码:
public class AlarmReceiver extends BroadcastReceiver {
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 180000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 180000;
@Override
public void onReceive(Context context, Intent intent) {
String ShiftID = intent.getExtras().getString("ShiftID");
Log.e("AlarmReceiver", "onReceive() ShiftID : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() ShiftID : " + ShiftID);
if(context==null)
{
Log.e("AlarmReceiver","Context:null");
}
else
{
Log.e("AlarmReceiver","Context:Not null");
}
String ops = intent.getExtras().getString("ops");
Log.e("AlarmReceiver", "onReceive() ops : " + ops);
common.writelog("AlarmReceiver", "onReceive() ops : " + ops);
if (ops.equals("s")) {
try {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean statusOfGPS = manager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*
* if (!statusOfGPS) { showGPSDisabledAlertToUser(); }
*/
// startAt10();
// start();
common.Running = true;
buildGoogleApiClient(context);
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
} catch (Exception ex) {
Log.e("AlarmReceiver", "onReceive() Error: 48 : " + ex.getMessage());
common.writelog("AlarmReceiver", "onReceive() ShiftID : " + ex.getMessage());
}
Log.e("AlarmReceiver", "onReceive() Start Service : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() Start Service : " + ShiftID);
Intent serviceIntent = new Intent(context, MyService.class);
serviceIntent.putExtra("ShiftID", ShiftID);
serviceIntent.putExtra("ops", ops);
assert context != null;
context.startService(serviceIntent);
//context.startService(new Intent(context, MyService.class));
} else if (ops.equals("e")) {
Log.e("AlarmReceiver", "onReceive() End Service : " + ShiftID);
common.writelog("AlarmReceiver", "onReceive() End Service : " + ShiftID);
Intent serviceIntent = new Intent(context, MyService.class);
serviceIntent.putExtra("ShiftID", ShiftID);
serviceIntent.putExtra("ops", ops);
assert context != null;
context.stopService(serviceIntent);
}
}
protected synchronized void buildGoogleApiClient(Context contex) {
mGoogleApiClient = new GoogleApiClient.Builder(contex)
.addApi(LocationServices.API).build();
createLocationRequest();
}
private void createLocationRequest() {
try {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest
.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}catch (Exception ex)
{
common.writelog("AlarmReceiver", "createLocationRequest()86: " + ex.getMessage());
}
}
}
我的服务代码:
package com.expedite.apps.vehiclelocation;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.format.Time;
import android.util.Log;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyService extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 2f;
private static String NAMESPACE = "http://tempuri.org/";
private static String SOAP_ACTION_VISITED = "http://tempuri.org/setVechicleLocation";
private static String METHOD_SEND_LOCATION_DATA = "setVechicleLocation";
private static String URL = "http://vts.vayuna.com/Service.asmx";
public String buskey = "";
boolean isget = false;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
try {
Log.e(TAG, "LocationListener " + provider);
common.writelog(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
} catch (Exception ex) {
Log.d(TAG, "LocationListener() Error:48 " + ex.getMessage());
common.writelog(TAG, "LocationListener() Error:48 " + ex.getMessage());
}
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
try {
mLastLocation.set(location);
Time time = new Time();
time.setToNow();
if (common.lat != location.getLatitude() || common.lon != location.getLongitude() || common.minut != time.minute) {
common.lat = location.getLatitude();
common.lon = location.getLongitude();
common.accu = location.getAccuracy();
common.minut = time.minute;
common.time = time.hour + ":" + time.minute + ":" + time.second;
new MyTask().execute();
common.writelog(TAG, "onLocationChanged: " + location.getAccuracy());
} else {
}
// Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
common.writelog(TAG, "onStatusChanged: " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
common.writelog(TAG, "onProviderEnabled: " + provider);
}
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
common.writelog(TAG, "onProviderDisabled: " + provider);
}
}
/* LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};*/
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER)
};
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Log.e(TAG, "onStartCommand");
common.writelog(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
} catch (Exception ex) {
Log.d(TAG, "onStartCommand() Error:120 " + ex.getMessage());
common.writelog(TAG, "onStartCommand() Error:120 " + ex.getMessage());
return 0;
}
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
common.writelog(TAG, "onCreate");
DatabaseHandler DB = new DatabaseHandler(getApplicationContext());
String Res = DB.ConvStrBusMaster();
if (!Res.equals("")) {
try {
String[] respons = Res.split("#@#@");
buskey = respons[3].toString();
Log.e("MyService", "onCreate() buskey"+buskey);
common.writelog("MyService", "onCreate() buskey"+buskey);
} catch (Exception ex) {
common.writelog("MyService::onCreate()", "Error: 121 MSG:" + ex.getMessage());
Log.e("MyService", "onCreate() Error: 121 MSG:" + ex.getMessage());
}
}
/* Log.e(TAG, "onCreate");
common.writelog(TAG, "onCreate");
if (isget == false) {
buskey =common.busid;
isget = true;
}*/
initializeLocationManager();
/* try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
common.writelog(TAG, "fail to request location update, ignore::: "+ ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
common.writelog(TAG, "network provider does not exist, " + ex.getMessage());
}*/
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
common.writelog(TAG, "fail to request location update, ignore::: "+ ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
common.writelog(TAG, "gps provider does not exist " + ex.getMessage());
}
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
try {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}catch ( Exception ex)
{
Log.d(TAG, "initializeLocationManager() Error:202 " + ex.getMessage());
common.writelog(TAG, "initializeLocationManager() Error:202 " + ex.getMessage());
}
}
private class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
SendDataToServer();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
public void SendDataToServer() {
// $,GJ05AV4839,4503791073,140416111538,21.172227,72.849145,0,0,0,0,#
SoapObject request = new SoapObject(NAMESPACE,
METHOD_SEND_LOCATION_DATA);
Time time = new Time();
String LocationDetails = "";
try {
if (common.lat != 0.0 && common.lon != 0.0) {
time.setToNow();
String m_androidId = "Service "
+ Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy:HH:mm:ss");
String currentTimeStamp = dateFormat.format(new Date());
/*LocationDetails = "$,XPD55," + time.hour + ":" + time.minute
+ ":" + time.second + "," + common.time + " Accuracy:"
+ common.accu + "," + common.lat + "," + common.lon
+ ",0,0,0," + m_androidId + ",#";*/
LocationDetails="$," + buskey + "," + buskey + "," + currentTimeStamp + "," + common.lat + ","
+ common.lon + ",0,0,Accuracy:" + common.accu + ",0,#";
common.writelog("Service", "SendLocation() 311:"+ common.lat+","+ common.lon+","+common.accu+", Details::"+LocationDetails+" , Url:"+URL);
request.addProperty("vehicleinfo", LocationDetails);
request.addProperty("device", buskey);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,
100000);
androidHttpTransport.call(SOAP_ACTION_VISITED, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
common.writelog("MyService","SendDataToServer()"+LocationDetails);
}
} catch (Exception ex) {
common.writelog("Service", "Exception 288:" + ex.getMessage()
+ ":::/n" + ex.getStackTrace());
}
}
}