Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: LGPL 

import android.annotation.SuppressLint;
import android.content.Context;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import android.text.TextUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class Main {

    @SuppressLint("HardwareIds")
    static String getPhoneMacAddress(Context context) {
        String mac = "";

        InputStreamReader inputStreamReader = null;
        LineNumberReader lineNumberReader = null;
        try {
            @SuppressLint("WifiManagerPotentialLeak")
            WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = manager.getConnectionInfo();
            mac = info.getMacAddress();

            if (TextUtils.isEmpty(mac)) {
                Process process = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
                inputStreamReader = new InputStreamReader(process.getInputStream());
                lineNumberReader = new LineNumberReader(inputStreamReader);
                String line = lineNumberReader.readLine();
                if (line != null) {
                    mac = line.trim();
                }
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (lineNumberReader != null) {
                try {
                    lineNumberReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        if (TextUtils.isEmpty(mac)) {
            mac = "na";
        }

        return mac;
    }
}