Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

I have two classes: one of these is an activity class and the other is non-activity. And I call a method which is inside the non-activity class for returning mac Adress.

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 non-activity 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 return null. I have the permission ACCESS_WIFI_STATE.

like image 570
Taha Avatar asked Oct 06 '22 12:10

Taha


2 Answers

if your wifi is not enable on the device , it will return null as your case , check if the wifi is enabled then if its enabled return the mac address else notify the user to enable the wifi .

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;
    }

}

}

like image 150
confucius Avatar answered Oct 10 '22 03:10

confucius


    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 didn't run the code but this is hw its to be done

like image 33
Terril Thomas Avatar answered Oct 10 '22 03:10

Terril Thomas