0

I figured out that my tablet with android 4.0.3 stops here while my phone with 2.2.3 works on this code but I do not know why:

I can not think of a difference between the tablet and phone coding, someone?

/* Store this device macaddress within the server. */
    static void storeMacAddress(final Context context, final String macAddr) { 
        Log.i(TAG, "Store device on Server (macAddress = " + macAddr + ")");
        String serverUrl = SERVER_URLL;
        Map<String, String> params = new HashMap<String, String>();
        params.put("macaddress", macAddr);

        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
        // As the server might be down, we will retry it a couple times.
        for (int i = 1; i <= MAX_ATTEMPTS; i++) {
            Log.d(TAG, "Attempt #" + i + " to store");
            try {
                post(serverUrl, params);
                Log.d(TAG, "Store op Server gelukt!");
                return;
            } catch (IOException e) {
                // Here we are simplifying and retrying on any error
                Log.e(TAG, "Failed to store on attempt " + i + ":" + e);
                if (i == MAX_ATTEMPTS) {
                    break;
                }
                try {
                    Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                    Thread.sleep(backoff);
                } catch (InterruptedException e1) {
                    // Activity finished before we complete - exit.
                    Log.d(TAG, "Thread interrupted: abort remaining retries!");
                    Thread.currentThread().interrupt();
                    return;
                }
                // increase backoff exponentially
                backoff *= 2;
            } 
        }

        Log.d(TAG, "Error tijdens store op Server procedure!");        
    }

private static void post(String endpoint, Map<String, String> params)
            throws IOException {    

        URL url;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=')
                    .append(param.getValue());
            if (iterator.hasNext()) {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        try {
            Log.e("URL", "> " + url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            // handle the response
            int status = conn.getResponseCode();
            if (status != 200) {
              throw new IOException("Post failed with error code " + status);
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
      }

EDIT: Calling from:

...    
setContentView(R.layout.activity_main);

            final SharedPreferences prefs = this.getSharedPreferences("nl.easy.winkel", Context.MODE_PRIVATE);

            if(!prefs.getString("macaddress","").equals("send")) { // Send MacAddress once
                prefs.edit().putString("macaddress","send").commit();
                obtainMacAddress();
            }

and 

    private void obtainMacAddress() {
            WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInf = wifiMan.getConnectionInfo();
            String macAddr = wifiInf.getMacAddress();
            final Context context = this;
            ServerUtilities.storeMacAddress(context, macAddr + "|" + getLocalIpAddress());
    }

        public String getLocalIpAddress() {
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e(TAG, ex.toString());
            }
            return null;
        }

EDIT2: using AsyncTask

AsyncTask<Void, Void, Void> mStoreTask;

private void obtainMacAddress() {
        WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInf = wifiMan.getConnectionInfo();
        final String macAddr = wifiInf.getMacAddress();
        final Context context = this;

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

            @Override
            protected Void doInBackground(Void... params) {
                // Store on our server
                // On server creates a new user
                ServerUtilities.storeMacAddress(context, macAddr + "|" + getLocalIpAddress());
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                mStoreTask = null;
            }

        };
        mStoreTask.execute(null, null, null);
    }
Harry
  • 786
  • 1
  • 8
  • 27

1 Answers1

4

There are two Solution of this Problem but first one is great solution.

1) Don't write network call in Main UI Thread, Use Async Task for that.

2) Write below code into your MainActivity file after setContentView(R.layout.activity_main); but this is not proper way.

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

And below import statement into your java file.

import android.os.StrictMode;

And see below link for more information.

Caused by: android.os.NetworkOnMainThreadException

Community
  • 1
  • 1
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
  • 1
    Don't use 2) - it's enabled for a [reason](http://developer.android.com/training/articles/perf-anr.html) – zapl Nov 29 '12 at 11:24
  • Thanks for reply but 2) can not be used in API 8 and I like the app available for API 8 and higher. See added edit where I am calling from. – Harry Nov 29 '12 at 11:59
  • @Harry In my code i already checked api level, if api level is greater than 9 then Strictmode is called otherwise not. – Dipak Keshariya Nov 29 '12 at 12:11
  • I saw, but eclipse gives a build error with Android 2.2 API 8. However, I correct the code with your 1) advise and it works! I edit the question with the new part. The only thing I do not understand is the IP output: I get 50:CC:F8:4B:65:93|fe80::52cc:f8ff:fe4b:6593%wlan0 as macAddr from tablet and 50:CC:F8:4B:65:93|192.168.xxx.xxx from phone, do you? – Harry Nov 29 '12 at 14:56