怎么才能从activity中传gps的值到myservice中,我的gps数据传不过去,求大佬解答
public class MainActivity extends Activity {
//地图相关
Workspace mWorkspace;
MapView mMapView;
private static Map m_map;
private ZoomControls m_zoom;
private LocationManager gpsLocationManager;
public static Location lastLocation = null;
private static Navigation mNavigation;
private static Track m_track;
private ImageButton ib_loc;
private int screenWidth;
private int screenHeight;
String rootPath = android.os.Environment.getExternalStorageDirectory ().getAbsolutePath ();
//设置全局变量并初始化
Point2D curLocation = new Point2D ( );
Point2D point2d= new Point2D ( );
private static Point2D mPoint;
//是否第一次定位,如果是第一次定位的话要将自己的位置显示在地图中间
boolean isFirstOpen = true;
//轨迹相关
public static boolean m_EnableLocationService;
private Button btn_recording,btn_stop;
private Layers m_Layers;
public static double mlocationY,mlocationX;
private boolean m_ExitEnable = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
power();
Environment.setLicensePath ( rootPath + "/SuperMap/license/" );
Environment.setTemporaryPath ( rootPath + "/SuperMap/temp/" );
Environment.setWebCacheDirectory ( rootPath + "/SuperMap/WebCache/" );
Environment.initialization ( this );
startMyLocationServerce ();
// 隐藏标题栏
requestWindowFeature ( Window.FEATURE_NO_TITLE );
// 隐藏状态栏
getWindow ().setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN );
WindowManager manager = getWindowManager ();
screenWidth = manager.getDefaultDisplay ().getWidth ();
screenHeight = manager.getDefaultDisplay ().getHeight ();
setContentView ( R.layout.activity_main );
//打开地图
openMap ();
//获取地图控件
initView ();
//定位监听
initLocationListener ();
//第一次定位返回定位点
firstLocation ();
initTrack ();
}
private void power() {
List<String> permissionList = new ArrayList<> ();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.READ_PHONE_STATE);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.RECORD_AUDIO);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.CAMERA);
}
if (!permissionList.isEmpty()) {
String[] permissions = permissionList.toArray(new String[permissionList.
size()]);
ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
} else {
}
}
private void initView() {
m_zoom = (ZoomControls)findViewById(R.id.zoomControls1);
mMapView = (MapView)findViewById(R.id.mapView);
m_zoom.setIsZoomInEnabled(true);
m_zoom.setIsZoomOutEnabled(true);
ib_loc = findViewById ( R.id.ib_loc );
btn_recording = findViewById ( R.id.btn_recording );
btn_stop = findViewById ( R.id.btn_stop );
//放大按钮
m_zoom.setOnZoomInClickListener(new View.OnClickListener(){
public void onClick(View v) {
m_map.zoom(2);
m_map.refresh();
}
});
//缩小按钮
m_zoom.setOnZoomOutClickListener(new View.OnClickListener(){
public void onClick(View v) {
m_map.zoom(0.5);
m_map.refresh();
}
});
//返回当前位置
ib_loc.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
m_map.setCenter ( point2d );
m_map.refresh ();
}
} );
btn_recording.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
track();
updateLocation ();
}
} );
btn_stop.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
m_track.stopTrack ();
m_EnableLocationService = false;
}
} );
m_map.refresh();
}
private void firstLocation(){
MapControl mapControl = mMapView.getMapControl ();
mapControl.zoomTo ( 1,50000 ); //设置地图缩放等级
TextView tv1;
tv1 = findViewById ( R.id.tv1 );
if(lastLocation != null){
if(isFirstOpen){
m_map.setCenter ( point2d );
m_map.refresh ();
}
isFirstOpen = false;
System.out.print ("======================" + point2d );
double la = lastLocation.getLatitude ();
double lo = lastLocation.getLongitude ();
//测试用,所获取的是第一次定位的信息
tv1.setText ( "维度:" + (la ) + "\n经度" + (lo ));
} else {
tv1.setText ( "无法获取地理信息" );
}
}
private void openMap() {
// 打开工作空间
mWorkspace = new Workspace ();
WorkspaceConnectionInfo info = new WorkspaceConnectionInfo ();
info.setServer ( rootPath + "/HiShow/SuperMap/mapData/mqdemo.smwu" );
info.setType ( WorkspaceType.SMWU );
mWorkspace.open ( info );
mMapView = (MapView) findViewById ( R.id.mapView );
MapControl mapControl = mMapView.getMapControl ();
m_map = mapControl.getMap ();
m_map.setWorkspace ( mWorkspace );
String mapName = mWorkspace.getMaps ().get ( 0 );
m_map.open ( mapName );
m_map.refresh ();
mNavigation = mapControl.getNavigation ();
mNavigation.setEncryption ( new SuperMapPatent () );
mapControl.setMapParamChangedListener ( mapParameterChangedListener );
}
//使用gps定位自己
private void initLocationListener() {
gpsLocationManager = (LocationManager) this
.getSystemService ( Context.LOCATION_SERVICE );
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;
}
lastLocation = gpsLocationManager
.getLastKnownLocation ( LocationManager.GPS_PROVIDER );
gpsLocationManager.requestLocationUpdates ( LocationManager.GPS_PROVIDER,
1, 1, locationListener );
}
//自定义gps定位自己的监听
private final LocationListener locationListener = new LocationListener () {
//Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
public void onStatusChanged(String provider, int status, Bundle extras) {
updateLocation ();
}
//Provider被enable时触发此函数,比如网路被打开
public void onProviderEnabled(String provider) {
}
//Provider被disable时触发此函数,比如网路被关闭
public void onProviderDisabled(String provider) {
}
//当坐标改变时触发函数
public void onLocationChanged(Location location) {
lastLocation = location;
updateLocation ();
}
};
private final MapParameterChangedListener mapParameterChangedListener = new MapParameterChangedListener () {
@Override
public void scaleChanged(double arg0) {
updateLocation ();
}
@Override
public void boundsChanged(Point2D arg0) {
updateLocation ();
}
@Override
public void angleChanged(double v) {
}
@Override
public void sizeChanged(int i, int i1) {
}
};
@Override
protected void onDestroy() {
super.onDestroy ();
gpsLocationManager.removeUpdates ( locationListener );
mMapView.getMapControl ().removeMapParamChangedListener (
mapParameterChangedListener );
}
@Override
protected void onResume() {
super.onResume ();
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;
}
// 设置监听器,自动更新的最小时间为间隔N秒(1秒为1*1000)或最小位移变化超过N米
gpsLocationManager.requestLocationUpdates ( LocationManager.GPS_PROVIDER,
1, 1, locationListener );
}
@Override
protected void onPause() {
super.onPause ();
// 取消注册监听
gpsLocationManager.removeUpdates ( locationListener );
}
//更新本地经纬度数据
private void updateLocation() {
if (lastLocation == null) {
return;
}
// sp = getSharedPreferences("lastLocation", Context.MODE_PRIVATE);
// String mSLocationx = sp.getString("latitude", "0.0");
// String mSLocationy = sp.getString("longitude", "0.0");
// Double mLocationx = Double.valueOf(mSLocationx);
// Double mLocationy = Double.valueOf(mSLocationy);
//地理位置纠偏
curLocation.setX ( lastLocation.getLongitude () + 0.0055 );//经度
curLocation.setY ( lastLocation.getLatitude () + 0.015 );//维度
//地理坐标与投影坐标的转换
PrjCoordSys Prj = m_map.getPrjCoordSys ();
if (Prj.getType () != PrjCoordSysType.PCS_EARTH_LONGITUDE_LATITUDE) {
Point2Ds points = new Point2Ds ();
points.add ( curLocation );
PrjCoordSys desPrjCoorSys = new PrjCoordSys ();
desPrjCoorSys.setType ( PrjCoordSysType.PCS_EARTH_LONGITUDE_LATITUDE );
CoordSysTranslator.convert ( points, desPrjCoorSys, Prj, new CoordSysTransParameter (), CoordSysTransMethod.MTH_GEOCENTRIC_TRANSLATION );
curLocation = points.getItem ( 0 );
mlocationY = curLocation.getY ();
mlocationX = curLocation.getX ();
//从控制台查看想X、Y的值
// System.out.println ( mlocationX );
// System.out.println(mlocationY);
point2d.setX ( mlocationX );
point2d.setY ( mlocationY );
GeoPoint gpsgeoPoint = new GeoPoint ();
gpsgeoPoint.setX ( mlocationX );
gpsgeoPoint.setY ( mlocationY );
addCallByName(gpsgeoPoint);
}
}
private void addCallByName(GeoPoint gps){
mMapView.removeAllCallOut ();
CallOut callout = new CallOut ( MainActivity.this );
callout.setStyle ( CalloutAlignment.CENTER );
callout.setCustomize ( true );
callout.setLocation ( gps.getX (), gps.getY () );
ImageView image = new ImageView ( MainActivity.this );
image.setBackgroundResource ( R.drawable.location );
callout.setContentView ( image );
mMapView.addCallout ( callout );
}
public void startMyLocationServerce(){
new Thread(new Runnable() {
@Override
public void run() {
Intent intentService = new Intent();
intentService.setAction ( "com.lcdx.supermap.myapplication.MyLocationService.START" );
//从3.1以后要注册动态广播
intentService.setClass(MainActivity.this, MyLocationService.class);
startService(intentService);
}
}).start();
}
private void initTrack(){
if (m_track != null){
// 设置用户传入GPS数据
m_track.setCustomLocation(true);
// 设置距离间隔为3米
m_track.setDistanceInterval(3);
// 设置时间间隔为1s
m_track.setTimeInterval(20);
// 设置匹配道路所在的数据集
m_track.setMatchDatasets(m_map.getWorkspace().getDatasources().get("road").getDatasets());
m_track.setCustomLocation(false);
}
}
/**
* 设置用于轨迹记录的GPS数据
* @param gpsData
*/
private static int count = 0;
public static void setGpsData(LocationManagePlugin.GPSData gpsData){
if(m_track != null){
//创建point2d
Point2D mPoint = mNavigation.encryptGPS ( gpsData.dLongitude,gpsData.dLatitude );
gpsData.dLongitude = mPoint.getX ();
gpsData.dLatitude = mPoint.getX ();
m_track.setCustomLocation ( false );
m_track.setGPSData ( gpsData );
count ++;
}
if(50 == count){
m_map.refresh ();
count = 0;
}
}
private void track() {
System.out.println("================================6");
Datasource m_Datasource = m_map.getWorkspace().getDatasources().get("track");
System.out.println("================================7");
m_Layers = m_map.getLayers();
System.out.println("================================8");
// 创建数据集
DatasetVector dataset = m_track.createDataset(m_Datasource, "qwe");
System.out.println("================================9");
//设置数据集的投影信息
PrjCoordSys Prj = m_map.getPrjCoordSys();
if (Prj.getType() != PrjCoordSysType.PCS_EARTH_LONGITUDE_LATITUDE) {
PrjCoordSys desPrjCoorSys = new PrjCoordSys();
desPrjCoorSys.setType(PrjCoordSysType.PCS_EARTH_LONGITUDE_LATITUDE);
dataset.setPrjCoordSys(desPrjCoorSys);
}
//设置轨迹记录的数据集为datas
m_track.setDataset(dataset);
System.out.println("================================10");
//开始轨迹记录
m_track.startTrack();
System.out.println("================================11");
clearLayers();
System.out.println("================================12");
//添加在图层轨迹记录的点数据
m_Layers.add(dataset, true);
System.out.println("================================13");
System.out.println(dataset + "****************************dataset");
m_EnableLocationService = false;
System.out.println("================================14");
//刷新地图
m_map.refresh();
System.out.println("================================15");
//开启定位
updateLocation ();
}
/**
* 清除除了底图以外的图层
*/
private void clearLayers() {
int count = m_Layers.getCount();
for (; count > 1; ) {
m_Layers.remove(0);
count = m_Layers.getCount();
}
}
}
public class MyLocationService extends Service {
public static double mlocationY,mlocationX;
public static double douX,douY;
private LocationManagePlugin.GPSData gpsData = new LocationManagePlugin.GPSData ();
private SharedPreferences sp;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("onDestroy");
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
mHandler.postDelayed(mRunnable, 400);
System.out.println("onStartCommand" + flags + "__" + startId);
return super.onStartCommand(intent, flags, startId);
}
Handler mHandler = new Handler ();
Runnable mRunnable = new Runnable () {
@Override
public void run() {
if (MainActivity.m_EnableLocationService) {
initGpsData();
MainActivity.setGpsData ( gpsData );
}
mHandler.postDelayed(mRunnable, 400);
}
};
private void initGpsData(){
douX = MainActivity.lastLocation.getLongitude ();
douY = MainActivity.lastLocation.getLatitude ();
gpsData.dLatitude = mlocationY;
gpsData.dLongitude = mlocationX;
System.out.println("=========我的Y"+mlocationY);
System.out.println("=========我的X"+mlocationX);
}
}