How can I use WifiManager in a non-activity class?

I have two classes: one of them is the activity class, and the other is inactive. And I call the method that is inside the non-activity class to return the mac address.

activity class:

public class Control extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    deneme d = new deneme(this); // i has tried (getApplicatonContext)
    String x = d.macadress();
    Toast.makeText(getApplicationContext(), x, Toast.LENGTH_LONG).show();
}}

and inactivity class:

public class deneme {
Context mcontext ;
WifiManager wm;

public deneme(Context mcontext){
    this.mcontext = mcontext;
}

public String macadress(){
    wm = (WifiManager)mcontext.getSystemService(Context.WIFI_SERVICE);
    String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
    return m_szWLANMAC;

}}

but the method returns null. I have permission ACCESS_WIFI_STATE.

+5
source share
3 answers

if your Wi-Fi is not turned on on the device, it will return null as your case, check if Wi-Fi is turned on, and then, if activated, returns a MAC address that once again notifies the user that Wi-Fi is turned on.

package com.example.wifitest;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.widget.Toast;

public class TEST {
    Context mcontext;
WifiManager wm;

public TEST(Context mcontext) {
    this.mcontext = mcontext;
}

public String macadress() {
    wm = (WifiManager) mcontext.getSystemService(Context.WIFI_SERVICE);
    if (wm.isWifiEnabled()) {
        String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
        return m_szWLANMAC;
    }
    else{
        Toast.makeText(mcontext, "Please enbale your wifi",
                Toast.LENGTH_SHORT).show();
        return null;
    }

}

}

+3
source
    public class MainActivity extends Activity {

        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        deneme d = new deneme(getApplicationContext()); 
  //  String x=d.wm.getConnectionInfo().getMacAddress();


      String x = d.macadress();
        Toast.makeText(getApplicationContext(), x, Toast.LENGTH_LONG).show();

    }


}
 class deneme {
Context mcontext ;
WifiManager wm;

public deneme(Context mcontext){
    this.mcontext = mcontext;
}

public String macadress(){
    wm = (WifiManager)mcontext.getSystemService(Context.WIFI_SERVICE);
    String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
    return m_szWLANMAC;

}}

I did not run the code, but this hw it needs to be done

+1
source

Context Activity non-Activity.

Here is a snippet from the network:

Class conectivityManager

Context myContext;

public conectivityManager(Context cxt){

myContext = cxt

}

public startWifi(){

//start-wifi

}

See this link:

http://www.brighthub.com/mobile/htc/articles/75491.aspx

0
source

All Articles