Android Studio 获取经纬度

需求详情

  • Service中每隔10秒执行一次定位操作(GPS+基站)
  • 定位的结果实时显示在E都市 上(要求得到经度、纬度)

Android Studio注册service服务

  • 切记android中的服务是需要在项目清单文件中注册的

首先新建service类,将所建的service添加到清单文件中

Android Studio 获取经纬度_第1张图片

具体创建并启动service方法可参考: Android Service与Activity的交互以及Android service服务

APP js中启动service服务示例代码

console.log("****************启动service服务:" + localStorage.getItem("$locationStatus"));
//获取Activity对象
var main = plus.android.runtimeMainActivity();
var Intent = plus.android.importClass('android.content.Intent');
var intent = new Intent();
// Activity绑定我们的service服务
intent.setClassName(main, "io.dcloud.HBuilder.wxapi.SingASongService");
// 设置需要传递的参数
intent.putExtra("userId", localStorage.getItem("$userId"));
intent.putExtra("url", CONFIG.server_url + "/apploginuser-apploginuser/apploginuser-save2.html");
// 启动service服务
main.startService(intent);
localStorage.setItem('$locationStatus','1');
console.log("****************启动service服务完毕:" +localStorage.getItem("$locationStatus"));

Android studio--Intent 介绍:关于启动service时的Intent介绍

service服务类逻辑示例代码

package io.dcloud.HBuilder.wxapi;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;

import org.apache.commons.httpclient.HttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.dcloud.HBuilder.R;

public class SingASongService extends Service {

    private MediaPlayer mMediaPlayer;
    private String url;   // 请求接口
    private String userId; // 用户ID
    private int taskId;    // 周期任务ID
    private Context context=this;
    private TestThread locationThread; //定时动态获取经纬度线程
    private Boolean isInterrupted = true;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        System.out.println("********SingASongService-->onCreate");
        super.onCreate();
        mMediaPlayer = MediaPlayer.create(this, R.raw.no_kill);
        mMediaPlayer.setLooping(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.url = intent.getStringExtra("url");
        this.userId = intent.getStringExtra("userId");
        System.out.println("**********url:"+url);
        System.out.println("************userId:"+userId);
        new Thread(new Runnable() {
            @Override
            public void run() {
                startPlaySong();
            }
        }).start();
        return START_NOT_STICKY;
    }

    //开始、暂停播放
    private void startPlaySong() {
        System.out.println("********SingASongService-->startPlaySong-->initLocation");
        if (null == locationThread){
            locationThread = new TestThread();
            locationThread.start();
        }else {
            locationThread.start();
        }
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.no_kill);
            mMediaPlayer.start();
        } else {
            mMediaPlayer.start();
        }
    }
    /**
     * 动态获取用户经纬度位置并向后台发送请求更新用户地图位置显示
     */
    public class TestThread extends Thread {

        public volatile boolean exit = false;
        public void run() {
            while (!exit){
                try{
                    if (this.interrupted()) {
                        System.out.println("**********************已经是停止状态了,我要退出了***********************");
                        break;
                    }
                    //初始化定位工具类
                    LocationUtils.initLocation(context);
                    System.out.println("GPS **********Location经度:"+LocationUtils.longitude);
                    System.out.println("GPS **********Location纬度:"+LocationUtils.latitude);

                    sendPost(url,"latitude="+LocationUtils.latitude+"&longitude="+LocationUtils.longitude+"&userId="+userId);
                    Thread.sleep(10000);//阻塞过程捕获中断异常来退出
                }catch(InterruptedException e){
                    e.printStackTrace();
                    System.out.println("*****************************捕获中断异常:跳出线程循环*********************");
                    break;//捕获到异常之后,执行break跳出循环。
                }
            }
        }
    }

    /**
     * 向后台发送请求更新用户位置
     * @param url 请求接口
     * @param param 经纬度以及用户ID
     * @return
     */
    public static String sendPost(String url, String param) {
        System.out.println("********param:"+param);
        System.out.println("********url:"+url);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        if (null != url){
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                System.out.println("********result"+result);
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
        }

        return result;
    }

    @Override
    public void onDestroy() {
        System.out.println("********SingASongService-->onDestroy");
        super.onDestroy();
        stopPlaySong();
        System.out.println("***********************调用方法终止线程");
        locationThread.exit = true;
        locationThread.interrupt();
        try {
            locationThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    //停止播放销毁对象
    private void stopPlaySong() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

}

 

js 停止service服务代码示例

console.log("*******************关闭service服务开启:"+localStorage.getItem("$locationStatus"));
var main = plus.android.runtimeMainActivity();
var Intent = plus.android.importClass('android.content.Intent');
var intent = new Intent();
intent.setClassName(main, "io.dcloud.HBuilder.wxapi.SingASongService");
main.stopService(intent);
localStorage.setItem('$locationStatus','0');
console.log("*******************关闭service服务完毕:"+localStorage.getItem("$locationStatus"));

首先开启Android定位的相关权限

Android Studio 获取经纬度_第2张图片

Android Studio中相关权限介绍:Android AndroidManifest 清单文件所有权限详解

LocationManager定位工具类示例代码

package io.dcloud.HBuilder.wxapi;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;

public class LocationUtils {
    // 纬度
    public static Double latitude = 0.0;
    // 经度
    public static Double longitude = 0.0;

    /**
     * 初始化位置信息
     *
     * @param context
     */
    public static void initLocation(Context context) {
        LocationListener locationListener = new LocationListener() {

            // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
            @Override
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {

            }

            // Provider被enable时触发此函数,比如GPS被打开
            @Override
            public void onProviderEnabled(String provider) {

            }

            // Provider被disable时触发此函数,比如GPS被关闭
            @Override
            public void onProviderDisabled(String provider) {

            }

            // 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
            @Override
            public void onLocationChanged(Location location) {
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
            }
        };
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        System.out.println("********locationManager:"+locationManager);
        // 检测GPS定位是否可用,不可用则进行网络定位(信号塔或WiFi定位的初略定位方式)
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            System.out.println("********locationManager.isProviderEnabled:"+LocationManager.GPS_PROVIDER);
            if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                Location location = locationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                System.out.println("********initLocation-->isProviderEnabled-->after-->latitude:"+latitude);
                System.out.println("********initLocation-->isProviderEnabled-->after-->longitude:"+longitude);
            }
        } else {

            locationManager
                    .requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            1000, 0, locationListener);
            Location location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                latitude = location.getLatitude(); // 经度
                longitude = location.getLongitude(); // 纬度
            }
            System.out.println("********initLocation-->after-->latitude:"+latitude);
            System.out.println("********initLocation-->after-->longitude:"+longitude);
        }
    }
}

关于Android Studio中获取经纬度的相关参考:

Android 定位的实现

Android Service获取当前位置(GPS+基站)

Android初级教程获取手机位置信息GPS与动态获取最佳方式

Android Studio 离线打包:Android平台本地(离线)打包指南

你可能感兴趣的:(Android Studio 获取经纬度)