简体   繁体   中英

How to get available wifi list from backend android service?

I am developing an android app which needs to check available wifi list periodically even when the app is killed from background. So I am thinking about using a service to check it from back end. In this case I am facing some problem to get the available wifi list from service. I search over internet and found most of the solution for activity only. Though I tried them but not working.

Please note that. THIS SAME CODE WORKS WHEN I USE THEM IN DIRECT ACTIVITY. BUT IT DOESN'T WORK IN SERVICE CLASS.

Code of my service is.....

package com.example.sodrulaminshaon.ringmodecontroller;


import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import java.util.List;
import java.util.Set;

/**
 * Created by Sodrul Amin Shaon on 22-Jun-18.
 */

public class MyService extends Service {
WifiManager wifiManager;
WifiReceiver receiverWifi;
private static final String LIST_TESTING = "ListTest";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCE_NAME,MODE_PRIVATE);
    boolean auto = preferences.getBoolean(Constants.AUTO_CONTROL_STR,false);
    //if(MainActivity.getAutoControl())
    if(auto)
    {
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled())
        {
            wifiManager.setWifiEnabled(true);
        }
        Log.i(LIST_TESTING,"Wifi is enabled. Now going to check the available list.");
        receiverWifi = new WifiReceiver();
        registerReceiver(receiverWifi,
                new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        wifiManager.startScan();
    }
    stopSelf();
    return START_STICKY;
}

class WifiReceiver extends BroadcastReceiver {

    // This method call when number of wifi connections changed
    public void onReceive(Context c, Intent intent) {

        StringBuilder sb = new StringBuilder();
        List<ScanResult> wifiList = wifiManager.getScanResults();
        Log.i(LIST_TESTING,"Inside scan result receiver. Scan result size: "+wifiList.size());
        sb.append("\n        Number Of Wifi connections :"+wifiList.size()+"\n\n");

        for(int i = 0; i < wifiList.size(); i++){

            sb.append(new Integer(i+1).toString() + ". ");
            sb.append(wifiList.get(i).SSID).toString();
            sb.append("\n\n");
        }
        Log.i(LIST_TESTING,sb.toString());
    }


}
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public void onDestroy() {
    // I want to restart this service again in one hour
    SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCE_NAME,MODE_PRIVATE);
    boolean auto = preferences.getBoolean(Constants.AUTO_CONTROL_STR,false);
    if(auto)
    {
        if(wifiManager.isWifiEnabled())unregisterReceiver(receiverWifi);
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarm.set(
                alarm.RTC_WAKEUP,
                System.currentTimeMillis() + (1000 * 10),
                PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
        );
    }
}

}

No need to worry about permission. I have taken necessary permissions at the start of the app. Still I am sharing the permission taken part.

private void getPermission(){
    if (ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            &&
            ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
        askForLocationPermissions();
    }
}
private void askForLocationPermissions() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.ACCESS_FINE_LOCATION)) {

        new android.support.v7.app.AlertDialog.Builder(this)
                .setTitle("Location permessions needed")
                .setMessage("you need to allow this permission!")
                .setPositiveButton("Sure", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                LOCATION_PERMISSION_REQUEST_CODE);
                    }
                })
                .setNegativeButton("Not now", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();

    } else {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                LOCATION_PERMISSION_REQUEST_CODE);
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
    switch (requestCode) {
        case LOCATION_PERMISSION_REQUEST_CODE:
            if (isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
            } else {
                Toast.makeText(this, "Can not proceed! i need permission" , Toast.LENGTH_SHORT).show();
            }
            break;
    }
}
public static boolean isPermissionGranted(@NonNull String[] grantPermissions, @NonNull int[] grantResults,
                                          @NonNull String permission) {
    for (int i = 0; i < grantPermissions.length; i++) {
        if (permission.equals(grantPermissions[i])) {
            return grantResults[i] == PackageManager.PERMISSION_GRANTED;
        }
    }
    return false;
} 

I can assure that my service is running well. It tries to check available wifi list each 10 seconds interval.

What I want to know is that. This code can not print the available wifi list. Just for the information in MyService class

Log.i(LIST_TESTING,"Wifi is enabled. Now going to check the available list.");

this line is printing continuously. But the other two lines

Log.i(LIST_TESTING,"Inside scan result receiver. Scan result size: "+wifiList.size());
Log.i(LIST_TESTING,sb.toString());

are not being executed. Can anyone please help me....

You should create a broadcast receivers to get the list of available wifi networks.

private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context c, Intent intent) {
            if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                List<ScanResult> mScanResults = mWifiManager.getScanResults();

            }
        }
    }

also add these lines in the manifest.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

and in oncreate() method register the listners

mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
registerReceiver(mWifiScanReceiver,
        new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();

For more details this question related to this POST .

As nobody is answering. I tried further and found the problem of my code. In my code I called stopSelf(); inside public int onStartCommand(Intent intent, int flags, int startId) method. Which was causing my service to stop just after it was started. Which means my registered broadCastReceiver was also being discarded. As a result wifi list was not being printed. I was dumb to write this code and finding the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM