Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何访问android服务中的外部类成员?_Java_Android - Fatal编程技术网

Java 如何访问android服务中的外部类成员?

Java 如何访问android服务中的外部类成员?,java,android,Java,Android,基本上,我有一个android服务日志服务,我从我的MainActivity中触发它。在服务类内部,我正在创建一个名为LocationFetcher的LocationListener类LocationFetcher的对象。LocationFetcher类具有公共字符串成员FormattedResult。现在,在LogService.run()中,我希望定期获取FormattedResult。怎么做??以下是参考代码 我有这样一个LocationListener: /*This is releva

基本上,我有一个android服务日志服务,我从我的MainActivity中触发它。在服务类内部,我正在创建一个名为LocationFetcher的LocationListener类LocationFetcher的对象。LocationFetcher类具有公共字符串成员FormattedResult。现在,在LogService.run()中,我希望定期获取FormattedResult。怎么做??以下是参考代码

我有这样一个LocationListener:

/*This is relevant content of LocationFetcher.java */

public class LocationFetcher extends TimerTask implements LocationListener{

    public String FormattedResult;
    private boolean availableFlag;
    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub
        this.availableFlag=true;
        this.FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", arg0.getLatitude(),arg0.getLongitude());
        Log.d("LocationFetcher",this.FormattedResult);
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Log.d("LocationFetcher","This is Timer Run !!!");
    }}
我的android服务是这样的:

/* This is the relevant pert from LogService.java file*/

public class LogService extends Service{
    private Logger logger;
    private LocationFetcher locationFetcher;
    public LocationManager locationManager;
    private Timer timer1;

    @Override
    public int onStartCommand(Intent intent,int flags, int startId){
    super.onStartCommand(intent, flags, startId);
    if(!this.running){

        this.logger = new Logger();  //Initiated member from subclass
        this.logger.start();         //Started
        this.timer1 = new Timer();   //Timer for timed job          
        this.locationFetcher = new LocationFetcher();//THIS IS MY EXTERNAL CLASS in "LocationFetcher.java"  
                                      //I am using GPS data.
        this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if(this.locationFetcher != null){//NULLPointerException is thrown if I REMOVE this if ??WHY
            this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationFetcher);
            this.timer1.scheduleAtFixedRate(this.locationFetcher, 5000, 2000); 
         //Below Line still throws NullPointrException ??WHY
         //this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this.locationFetcher);

        }else{
            Log.d("GPS-Logger"," Found Null LocationFlecther !");
        }
    }
    public void run(){
        LogService ll = LogService.this;
        LocationManager mgr = ll.locationManager; //THIS IS MY QUESTION
        // HOW DO I ACCESS THE GPS LOCATION STORED in locationmanager.FormattedResult
        // Which is a string
        // //////////////////////////////////////////////////////////////////////////
        while(ll.isActive){

            try {

                String temp ;
                if(!temp.isEmpty()){
                    Log.d("GPS-Logger","data is :"+temp);
                }
                Log.d("GPS-Logger","data is :");
                Thread.sleep(5000);
                sec +=1 ;
                if(sec >= 12){
                    Log.d("GPS-Logger","Sending Data Here");
                    sec = 0;
                }

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                ll.isActive=false;
                Log.d("GPS-Logged","EXIT Request Received");
            }
        }
    }
我知道我在上面问了很多问题,但我不知道如何把它们分开。
需要帮助

您可以将位置获取程序修改为“LocationListenerClass”,如下所示:

在修改后的类中要看到的主要问题如下:

1.我使用了一个singleton类来注册和删除整个区域的位置更新(例如我们的服务等)

2.您应该从onLocationChngaed()和getCurrentLocation()初始化位置字符串say(在您的例子中为FormattedResult)。因为onLocationChngaed()只会在距离和时间发生变化时调用,如有关此问题的详细研究所述。

    public class LocationListenerClass implements LocationListener{
        private static LocationListenerClass instance;
        private static Context context;
        private LocationManager myLocationManager;
        private LocationListener myLocationListener;
        private Double latitude = 0d;
        private Double longitude = 0d;
public static String FormattedResult;
        public static LocationListenerClass getInstance(Context context) {
            LocationListenerClass.context = context;
            if (null == instance) {
                instance = new LocationListenerClass();
            }
            return instance;
        }

        public void getCurrentLocation() {
            try {
                myLocationManager = (LocationManager) context
                        .getSystemService(Context.LOCATION_SERVICE);

                myLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 30000, 100,
                        this);

                Location location;
                location = myLocationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                if (location == null) {
                    myLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER, 30000, 100,
                            myLocationListener);
                    location = myLocationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }

                if (location != null) {
                    try {
                        latitude = location.getLatitude();
                        Data.CURENT_LATITUDE = latitude;
                        Log.v(ConstantLib.LOG, " latitude : "
                                + Data.CURENT_LATITUDE);
                        longitude = location.getLongitude();
                        Data.CURENT_LONGITUDE = longitude;
                        Log.v(ConstantLib.LOG, " longitude : "
                                + Data.CURENT_LONGITUDE);

 **FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", latitude(),longitude());
        Log.d("LocationFetcher",this.FormattedResult);**

                    } catch (Exception e) {
e.printStackTrace();
                    }

                }
            } catch (Exception e) {
e.printStackTrace();
            }

        }

        public void removeLocationUpdates() {
            try {
                if (myLocationManager != null) {
                    myLocationManager.removeUpdates(myLocationListener);
                }
            } catch (Exception e) {
            }
        }



            public void onLocationChanged(Location location) {

                try {
                    if (location != null) {
                        Data.CURENT_LATITUDE = location.getLatitude();
                        Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " latitude : "
                                + Data.CURENT_LATITUDE);
                        longitude = location.getLongitude();
                        Data.CURENT_LONGITUDE = location.getLongitude();
                        Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " longitude : "
                                + Data.CURENT_LONGITUDE);

 **FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", latitude(),longitude());
        Log.d("LocationFetcher",this.FormattedResult);**
                    }
                } catch (Exception e) {
    e.printStackTrace();
                }

            }

            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }

            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub
            }
        }

公共静态字符串FormattedResult;//将其设置为静态,然后在服务类中以LocationFetcher.FormattedResult.LocationFetcher.FormattedResult的形式访问字符串。对于
静态
建议,如果您不了解自己在做什么,则这些建议是危险的@黄谷恩是对的。顺便说一下,不要在Android上使用计时器,而是通过
Handler
s或
View
方便功能运行。
计时器
是一个单独的
线程
,这在Android上是一种非常低效的方法。@ArpitGarg总是返回ig me null。还要注意,我是以字符串temp=LocationFetcher.FormattedResult访问它的。当LocationListener将使用最新的lat long上传该字符串时,将该字符串设置为静态是否合乎逻辑?@wy我不建议在服务中实现它。您所创建的LocationFetcher未捕获cordinates位置和最后一个已知位置。。它将只返回null