0

in my application i'm try to use this helpful document about get server time, but i get this error:

Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getByName(InetAddress.java:289)
            at ir.tsms.EitaaPro.Activities.ActivityBootstrap.getCurrentNetworkTime

my developed code is:

public static void getCurrentNetworkTime() {
    NTPUDPClient timeClient = new NTPUDPClient();
    timeClient.setDefaultTimeout(3000);
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByName(G.TIME_SERVER);
        TimeInfo timeInfo = null;
        timeInfo = timeClient.getTime(inetAddress);
        long localTime = timeInfo.getReturnTime();   //local device time
        long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();   //server time

        Log.e("Time from local: ", " " + new Date(localTime));
        Log.e("Time from server: ", " " + new Date(serverTime));
    }catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

try and catch statement doesnt work in this code and i'm set all internet and network permissions in manifest

Community
  • 1
  • 1

2 Answers2

0

You are doing network access in main thread so you got that exception. You need to use asynctask to do network related task.

for example :-

new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPreExecute() {
            //you can show a progress dialog here
        }

        @Override
        protected Void doInBackground(Void... params) {
            //do your network task here
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            //dismiss the progress dialog here or do any main thread task
        }
    }.execute();
}

For full tutorial try this :- http://samir-mangroliya.blogspot.in/p/android-asynctask-example.html

Hope this help you :)

Biswajit
  • 1,829
  • 1
  • 18
  • 33
0

Networking operations are the type of operations that should be running in background so it doesn't effect the main thread and freez the app, these type of operations should use an asyncTask and here is a good example that may be used in your situation: AsyncTask Android example you can also check the documentation for more info.

Community
  • 1
  • 1
Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56