首页 > 解决方案 > 使用 OnSuccessListener 然后在方法中使用 PrintStream 会出错

问题描述

我正在使用 Google API 来获取设备的位置,我必须使用 OnSuccessListener 但我尝试使用 PrintStream 所以它在成功时发送位置但它给了我一个 NetworkOnMainThreadException

我尝试使用处理程序,我看到我可以使用 AsyncTask 但我不知道在哪里,我真的认为问题出在 onSuccess 但我找不到任何有帮助的东西

@Override

        public void onSuccess(Location location)
        {
            if(location != null){

                Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
                List<Address> addresses = null;

                try {
                    addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

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

                clientConnection.sendtoServer("loc",addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea());//this line is the problem 

            }
            else
                clientConnection.sendtoServer("loc","Not Found!");
        }

clientConnection.sendtoServer 是问题

//this is used for a Socket the class of the socket is clientConnection

public static void sendtoServer(String TextCode,String message){
        os.println(TextCode+" "+message);
        os.flush();
    }

这是我的错误

2019-01-01 19:24:51.037 7077-7077/com.example.victor.zactarget E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.victor.zactarget, PID: 7077
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:157)
    at java.io.PrintStream.write(PrintStream.java:492)
    at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
    at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
    at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
    at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
    at java.io.PrintStream.write(PrintStream.java:543)
    at java.io.PrintStream.print(PrintStream.java:687)
    at java.io.PrintStream.println(PrintStream.java:824)
    at com.example.victor.zactarget.ClientConnection.sendtoServer(ClientConnection.java:118)
    at com.example.victor.zactarget.Code$2.onSuccess(Code.java:66)
    at com.example.victor.zactarget.Code$2.onSuccess(Code.java:54)
    at com.google.android.gms.tasks.zzn.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6688)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

标签: androidgoogle-mapssocket.io

解决方案


我找到了答案,但我仍然认为它可以做得更好

public static void sendLocation(final ClientConnection clientConnection) throws InterruptedException
{


    final boolean[] ready = new boolean[1];
    final String[] locationString = new String[1];

    client = LocationServices.getFusedLocationProviderClient(activityContext);

    if (ActivityCompat.checkSelfPermission(activityContext, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        clientConnection.sendtoServer("loc","Denied");
    }

    client.getLastLocation().addOnSuccessListener(activityContext, new OnSuccessListener<Location>() {

        @Override
        public void onSuccess(Location location)
        {
            if(location != null){

                Geocoder geocoder = new Geocoder(activityContext.getApplicationContext(), Locale.getDefault());
                List<Address> addresses = null;

                try {
                    addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

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

                locationString[0] = addresses.get(0).getCountryName()+","+addresses.get(0).getAdminArea();

                /*
                String address = addresses.get(0).getSubLocality();
                String cityName = addresses.get(0).getLocality();
                String stateName = addresses.get(0).getAdminArea();
                String countryName = addresses.get(0).getCountryName();
                */

            }
            else
                locationString[0] ="Not Found!";

            ready[0] = true;
        }
    });

    while (ready[0] != true){
        TimeUnit.MILLISECONDS.sleep(500);
    }

    clientConnection.sendtoServer("loc", locationString[0]);
}

推荐阅读