GPS Плагин Андроид

Программирование для iPhone & Android

GPS Плагин Андроид

Сообщение niklas1987 11 апр 2015, 12:41

Здравствуйте. Уже очень долго мучаюсь, не могу решить эту проблему.
На сколько мне известно GPS API Unity3d не выдает getSpeed()
Я начал писать свой GPS плагин.
Файл Speedometer.java
Синтаксис:
Используется javascript
package com.zaqxs1995.speedometer;
import com.unity3d.player.UnityPlayerActivity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Config;
import android.util.Log;
public class Speedometer extends UnityPlayerActivity {

    private static final String TAG = "GPS_Unity";
   
    public static Location currentLocation;
    public static LocationManager myLocationManager;  
 
    static LocationListener networkLocationListener;
    static LocationListener gpsLocationListener;
   
    public static void startLocationListeners() {        
        gpsLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                currentLocation = location;
                Log.i(TAG, "Getting Location over GPS " + currentLocation.toString());
            }
            public void onProviderDisabled(String provider) {
            }
            public void onProviderEnabled(String provider) {
            }
            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
            }
        };        
        networkLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                currentLocation = location;
                Log.i(TAG,
                        "Getting Location over GPS" + currentLocation.toString());
            }
            public void onProviderDisabled(String provider) {
            }
            public void onProviderEnabled(String provider) {
            }
            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
            }
        };
        myLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0,
                networkLocationListener);
        myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                gpsLocationListener);
    }
    @Override
    protected void onCreate(Bundle myBundle) {
        super.onCreate(myBundle);
        myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);        
        startLocationListeners();
    }
    @Override
    protected void onResume() {
        if (Config.DEBUG)
            Log.d(TAG, "onResume");
        super.onResume();
        startLocationListeners();
    }
    @Override
    protected void onPause()
    {
        myLocationManager.removeUpdates(networkLocationListener);
        myLocationManager.removeUpdates(gpsLocationListener);
        super.onPause();
    }
    @Override
    protected void onStop() {
        if (Config.DEBUG)
            Log.d(TAG, "onStop");
        myLocationManager.removeUpdates(networkLocationListener);
        myLocationManager.removeUpdates(gpsLocationListener);
        super.onStop();
    }    
    public static String getSpeed()
    {
        if(currentLocation!=null)
            return "" + currentLocation.getSpeed()*3.6;
        else
            return "Unknown";
    }
}

Скомпилировал Jar в папку Assets\Plugins\Android

Создал GUIText, назвал его gps_output.
Создал GPSManager.cs в проекте и кинул его на камеру
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class GPSManager : MonoBehaviour {
        static string speedMessage;
        AndroidJavaClass gpsActivityJavaClass;
        void Start () {
                AndroidJNI.AttachCurrentThread();
                gpsActivityJavaClass = new AndroidJavaClass("com.zaqxs1995.speedometer.Speedometer");
        }
        void Update() {
                speedMessage = gpsActivityJavaClass.CallStatic<string>("getSpeed");
                float speed = 0;
                if(speedMessage!="Unknown")
                {
                        speed = float.Parse(speedMessage);
                        GameObject.Find("gps_output").GetComponent<GUIText>().text = speed + "км";
                }
                else
                {
                        GameObject.Find("gps_output").GetComponent<GUIText>().text = "Скорость не доступна.";
                }
        }
}


При открытии программы на телефоне она начинает искать спутники(мигает значок).
Но скорость в GUIText(gps_output) отправлять не хочет!

Вот что пишет в консоли:
NullReferenceException: Object reference not set to an instance of an object
GPSManager.Update () (at Assets/Location/GPSManager.cs:14)


А вот и сама 14 строчка в GPSManager.cs
Синтаксис:
Используется csharp
speedMessage = gpsActivityJavaClass.CallStatic<string>("getSpeed");

По моему я достаточно подробно объяснил Unity где экземпляр объекта... Но он его в упор видеть не хочет.
Есть у кого какие идеи?
niklas1987
UNец
 
Сообщения: 5
Зарегистрирован: 11 апр 2015, 12:11

Re: GPS Плагин Андроид

Сообщение niklas1987 12 апр 2015, 06:54

Скажите, я хоть правильно вызываю getSpeed()?

Синтаксис:
Используется csharp
AndroidJNI.AttachCurrentThread();
                gpsActivityJavaClass = new AndroidJavaClass("com.zaqxs1995.speedometer.Speedometer");

speedMessage = gpsActivityJavaClass.CallStatic<string>("getSpeed");
niklas1987
UNец
 
Сообщения: 5
Зарегистрирован: 11 апр 2015, 12:11

Re: GPS Плагин Андроид

Сообщение niklas1987 12 апр 2015, 10:03

Мда... походу придется спрашивать за бугром!
niklas1987
UNец
 
Сообщения: 5
Зарегистрирован: 11 апр 2015, 12:11

Re: GPS Плагин Андроид

Сообщение niklas1987 12 апр 2015, 15:18

Решено.
Если кому интересно, это просто unity тупит. на телефоне все ок.
Можно закрывать!
niklas1987
UNец
 
Сообщения: 5
Зарегистрирован: 11 апр 2015, 12:11

Re: GPS Плагин Андроид

Сообщение RRRR 25 окт 2019, 17:24

Делаю на этом примере библиотеку GPS на AndroidStudio 3.5.1 для Unity5.6.4

в формате AAR

Не работает,не приходит GPS информация,нужно исправить где-то...
...ошибка кроется похоже в допуске /** Check activity*/

оригинал ссылка
http://www.mat-d.com/site/unity-gps-plu ... e-and-ant/

Установил AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.location.gps" android:required="true" />
Добавил Class.jar в libs
добавил строчку
dependencies {
compileOnly files('libs/classes.jar')

Код AndroidStudio
Синтаксис:
Используется javascript
 

package com.name1.name2;

import android.Manifest;
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.app.ActivityCompat;
import com.unity3d.player.UnityPlayerActivity;


public class plugin extends UnityPlayerActivity {

    /** Stores the current location */
    public static LocationManager myLocationManager;
    static LocationListener networkLocationListener;
    static LocationListener gpsLocationListener;
    static Location currentLocation;
    private static Context activity;

    /** ---------------Start-----------------*/
    public static void startLocationListeners()  {
        /** Getting Location over GPS  + currentLocation*/
        gpsLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) { currentLocation = location; }
            public void onProviderDisabled(String provider) { }
            public void onProviderEnabled(String provider) { }
            public void onStatusChanged(String provider, int status, Bundle extras) { }
        };

        /** Getting Location over Network  + currentLocation*/
        networkLocationListener = new LocationListener()  {
            @Override
            public void onLocationChanged(Location location) { currentLocation = location; }
            public void onProviderDisabled(String provider) { }
            public void onProviderEnabled(String provider) { }
            public void onStatusChanged(String provider, int status, Bundle extras) { }
        };

        /** Check  activity*/
               if (ActivityCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                 return;
           }

        /** Update Location*/
        myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
        currentLocation = myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        myLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0, networkLocationListener);
        currentLocation = myLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);


        String provider = LocationManager.PASSIVE_PROVIDER;
        currentLocation = myLocationManager.getLastKnownLocation(provider);

    }


/**---------Start YES-------*/
    @Override
    protected void onCreate(Bundle myBundle) {
        super.onCreate(myBundle);
        myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        startLocationListeners();
    }
    @Override
    protected void onResume() {
        super.onResume();
        startLocationListeners();
    }
    @Override
    protected void onPause()
    {
        myLocationManager.removeUpdates(networkLocationListener);
        myLocationManager.removeUpdates(gpsLocationListener);
        super.onPause();
    }
    @Override
    protected void onStop() {
        myLocationManager.removeUpdates(networkLocationListener);
        myLocationManager.removeUpdates(gpsLocationListener);
        super.onStop();
    }

    /** ------------------Return --------String------*/

    /** Return  the Location */
    public static String getLat() {
        String latLongString = "NO INFO";
        if (currentLocation != null) {
            double lat = currentLocation.getLatitude();
            double lng = currentLocation.getLongitude();
            latLongString = "Lat: " + lat + "\nLong: " + lng;
            return "Location: " + latLongString;
        }
        else {return "Location: " + latLongString;}
    }

    /** Return  the Speed in km/h */
    public static String getSpeed()
    {
        if(currentLocation!=null){ return "Speed: " + currentLocation.getSpeed()*3.6;}
        else{return "Speed: Unknown";
        }
    }




    /** Return test Java to UNITY */
    public static String GetTextFromPlugin(int number){ return "Java YES " + number; }
} /** End  the class plugin */
 



Код UNITY Тестовый.Выводит информацию getSpeed
Синтаксис:
Используется csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PluginSpeed : MonoBehaviour {
         
        void Update () {
                TextMesh textMesh = GetComponent<TextMesh> ();
                #if UNITY_ANDROID && !UNITY_EDITOR
                var pluginSpeed = new AndroidJavaClass ("com.name1.name2.plugin");
                textMesh.text = pluginSpeed.CallStatic<string> ("getSpeed");
                #endif
        }
}
 
Последний раз редактировалось RRRR 26 окт 2019, 10:50, всего редактировалось 3 раз(а).
RRRR
UNец
 
Сообщения: 1
Зарегистрирован: 25 окт 2019, 12:03

Re: GPS Плагин Андроид

Сообщение Jarico 25 окт 2019, 17:59

Сейчас бы вызывать GetComponent каждый кадр... :)
Github: _https://github.com/redheadgektor
Discord: Конь! Чаю!#9382 (сижу редко)
YouTube: _https://www.youtube.com/channel/UCPQ04Xpbbw2uGc1gsZtO3HQ
Telegram: _https://t.me/redheadgektor
Аватара пользователя
Jarico
Адепт
 
Сообщения: 1084
Зарегистрирован: 06 янв 2019, 17:37
Откуда: 0xDEAD
Skype: none
  • Сайт


Вернуться в iPhone & Android

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 2