Android 获取所有可用的Wi-Fi信息并发送到mysql数据库

Android 获取所有可用的Wi-Fi信息并发送到mysql数据库,android,mysql,android-asynctask,Android,Mysql,Android Asynctask,我对java相当陌生,但我正在尝试创建一个定期收集WiFi信息、向用户显示并发送到数据库的应用程序 我有Wifi收集工作,它收集SSID、BSSID、RSSI和时间戳。它向用户显示,我甚至可以向服务器发送信息。 但是,我的当前代码没有正确地将数据发送到服务器。它发送数据,但卡在一个SSID、BSSID和RSSI上。例如,如果有20个无线网络,应用程序将发送19个相同的条目,并且可能将下一个条目作为第20个条目。 我相信这与函数InsertData中的asynctask有关,也许它比wifit

我对java相当陌生,但我正在尝试创建一个定期收集WiFi信息、向用户显示并发送到数据库的应用程序

我有Wifi收集工作,它收集SSID、BSSID、RSSI和时间戳。它向用户显示,我甚至可以向服务器发送信息。

但是,我的当前代码没有正确地将数据发送到服务器。它发送数据,但卡在一个SSID、BSSID和RSSI上。例如,如果有20个无线网络,应用程序将发送19个相同的条目,并且可能将下一个条目作为第20个条目。

我相信这与函数InsertData中的asynctask有关,也许它比wifithing函数运行得更快。但我不确定如何解决这个问题

谢谢大家的回复

更新

大家好

这里使用了两个函数wifithing()和InsertData(),其中包含一个异步任务,用于将数据发送到mysql数据库,wifithing()工作正常,并将SSID、BSSID和RSSI分配给要在别处显示的设备,它以循环方式在所有可用网络中循环执行此操作

现在,按下按钮调用InsertData(),并使用循环遍历所有可用网络。这确实有效,但我在数据库上看到了一些奇怪的结果,首先在开始时添加了一个重复条目,然后在第二次按下按钮时没有发送数据,第三次按下时有效,第四次按下时无效。。

编辑wififragment.java

    package com.example.joe.ratscanner;


    import android.Manifest;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.pm.PackageManager;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiManager;
    import android.os.AsyncTask;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.Toast;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.concurrent.Executor;

    //return inflater.inflate(R.layout.fragment_wifi, container, false);
    /**
     * A simple {@link Fragment} subclass.
     */
    public class wififragment extends Fragment {

        int count= 0;
        Timer t;
        String ServerURL = "http://ratscanner.duckdns.org/get_data.php" ;

        String TempWifi;
        String TempBSSID;
        String Templevel;
        String test;

        String isthishappening;


        TimerTask timer= new TimerTask(){

            @Override
            public void run() {

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //count--;
                        //if (count >= 0) {
                        if(count == 0) {


                            //Toast.makeText(getActivity(),"this updated",Toast.LENGTH_SHORT).show();
                              // wifithing();
                                //InsertData(); //probably remove this later


                        }
                    }
                });
                //if (count <= 0) {
                // t.cancel();
                //}
            }

        };





        public class device{
            CharSequence name;

            public String setName(CharSequence name) {
                this.name = name;
                return null;
            }

            public CharSequence getName (){
                return name;
            }
        }
        final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 125;
        List<ScanResult> wifiList;
        private WifiManager wifi;
        List<device> values = new ArrayList<device>();
        int netCount=0;
        int AnetCount=0;
        RecyclerView recyclerView;
        WifiScanAdapter wifiScanAdapter;

        public wififragment() {
            // Required empty public constructor
        }
        public static wififragment newInstance() {
            wififragment fragment = new wififragment();
            return fragment;
        }


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }



        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            //Make instance of Wifi
            Button btnScan= (Button) getActivity().findViewById(R.id.wifiScan);
            wifi = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            //Check wifi enabled or not
            if (wifi.isWifiEnabled() == false)
            {
                Toast.makeText(getActivity(), "Wifi is disabled enabling...", Toast.LENGTH_LONG).show();
                wifi.setWifiEnabled(true);
            }
            //register Broadcast receiver
            getActivity().registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    wifiList=wifi.getScanResults();
                    netCount=wifiList.size();
                    AnetCount=wifiList.size();
                    // wifiScanAdapter.notifyDataSetChanged();
                    Log.d("Wifi","Total Wifi Network"+netCount);
                }
            },new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

            wifiScanAdapter=new WifiScanAdapter(values,getContext());
            recyclerView= (RecyclerView) getActivity().findViewById(R.id.wifiRecyclerView);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            recyclerView.setAdapter(wifiScanAdapter);


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkandAskPermission();
            } else {
                wifithing();

            }

            btnScan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    wifithing();
                    InsertData();
                    InsertData();
                    Toast.makeText(getContext(), netCount +"\n"+ AnetCount , Toast.LENGTH_SHORT).show();

                }

            });
        }

 /*       public void wifithing(){
            SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy");
            wifi.startScan();
            values.clear();

            try {
                netCount = netCount - 1;
                while (netCount >= 0) {
                    String currentDateTimeString = dateformat.getDateTimeInstance().format(new Date());
                    device d = new device();

                    d.setName(wifiList.get(netCount).SSID.toString()+"\n"+ wifiList.get(netCount).BSSID +" "+ wifiList.get(netCount).level +"\n" + currentDateTimeString );
                    //TempWifi = d;//returns nothing, need to make it return ssid

                    //TempWifi = "";// clears the old data
                    TempWifi = wifiList.get(netCount).SSID.toString(); //adds the new ssid
                    TempBSSID = wifiList.get(netCount).BSSID.toString(); //adds the new bssid
                    Templevel = Integer.toString(wifiList.get(netCount).level);// adds the new level

                    //currently have issue where one/two ssids are put in database
                    // maybe see how many "SSIDS" database recieves and how many show up on scan
                    // 20 on server, 20 on app
                    //20 on server, 20 on app
                    //19 on server, 19 on app

                    isthishappening = "This is from wifithing";
                    InsertData();// calls the method which sends the data to server

                    Log.d("WiFi",d.getName().toString());
                    values.add(d);
                    wifiScanAdapter.notifyDataSetChanged();
                    netCount=netCount -1;
                }
            }
            catch (Exception e){
                Log.d("Wifi", e.getMessage());
            }

        }*/
       public void wifithing(){
            SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy");
            wifi.startScan();
            values.clear();

            try {
                netCount = netCount - 1;
                while (netCount >= 0) {
                    String currentDateTimeString = dateformat.getDateTimeInstance().format(new Date());
                    device d = new device();

                    d.setName(wifiList.get(netCount).SSID.toString()+"\n"+ wifiList.get(netCount).BSSID +" "+ wifiList.get(netCount).level +"\n" + currentDateTimeString );
                    //TempWifi = d;//returns nothing, need to make it return ssid



                    //currently have issue where one/two ssids are put in database
                    // maybe see how many "SSIDS" database recieves and how many show up on scan
                    // 20 on server, 20 on app
                    //20 on server, 20 on app
                    //19 on server, 19 on app

                    isthishappening = "This is from wifithing";
                    //InsertData();// calls the method which sends the data to server

                    Log.d("WiFi",d.getName().toString());
                    values.add(d);
                    wifiScanAdapter.notifyDataSetChanged();
                    netCount=netCount -1;
                }
            }
            catch (Exception e){
                Log.d("Wifi", e.getMessage());
            }

        }





        //this code is responsible for sending data to the server through PHP////////////////////////////////////////////////////////
        public void InsertData(){

            class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

                @Override
                protected String doInBackground(String... params) {

                    try {
                        AnetCount = AnetCount - 1;
                        while (AnetCount >= 0) {

                            TempWifi = wifiList.get(AnetCount).SSID.toString(); //adds the new ssid
                            TempBSSID = wifiList.get(AnetCount).BSSID.toString(); //adds the new bssid
                            Templevel = Integer.toString(wifiList.get(AnetCount).level);// adds the new level


                            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                            nameValuePairs.add(new BasicNameValuePair("SSID", TempWifi));
                            nameValuePairs.add(new BasicNameValuePair("MAC", TempBSSID));
                            nameValuePairs.add(new BasicNameValuePair("level", Templevel));


                            try {
                                HttpClient httpClient = new DefaultHttpClient();

                                HttpPost httpPost = new HttpPost(ServerURL);

                                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                                HttpResponse httpResponse = httpClient.execute(httpPost);

                                HttpEntity httpEntity = httpResponse.getEntity();


                            } catch (ClientProtocolException e) {

                            } catch (IOException e) {

                            }

                            AnetCount = AnetCount - 1;

                        }


                    }
                    catch (Exception e){
                        Log.d("Wifi", e.getMessage());
                    }
                    return "Data Inserted Successfully";
                }
                @Override
                protected void onPostExecute(String result) {
                    isthishappening = "This is from async";
                    Log.d("wifi", isthishappening);

                    //Log.d("wifi", result);
                    super.onPostExecute(result);

                    //Toast.makeText(getContext(), TempWifi, Toast.LENGTH_SHORT).show();

                }
            }
            SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

            sendPostReqAsyncTask.execute();

        }///////////////////////////////////////////////////////////////////////////////////////////////////////////////



        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {


            t = new Timer();
            t.scheduleAtFixedRate(timer , 10000 , 10000);
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_wifi, container, false);


        }

        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                               int[] grantResults) {
            switch (requestCode) {
                case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
                    Map<String, Integer> perms = new HashMap<String, Integer>();
                    perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);
                    if (perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        wifi.startScan();
                    } else {
                        // Permission Denied
                        Toast.makeText(getContext(), "Some Permission is Denied", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            }
        }

        private void checkandAskPermission() {
            List<String> permissionsNeeded = new ArrayList<String>();

            final List<String> permissionsList = new ArrayList<String>();
            if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
                permissionsNeeded.add("Network");


            if (permissionsList.size() > 0) {
                if (permissionsNeeded.size() > 0) {
                    // Need Rationale
                    String message = "You need to grant access to " + permissionsNeeded.get(0);
                    for (int i = 0; i < permissionsNeeded.size(); i++)
                        message = message + ", " + permissionsNeeded.get(i);
                    showMessageOKCancel(message,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                                }
                            });
                    return;
                }

                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                return;
            }
            // initVideo();
        }

        private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
            new AlertDialog.Builder(getActivity())
                    .setMessage(message)
                    .setPositiveButton("OK", okListener)
                    .setNegativeButton("Cancel", okListener)
                    .create()
                    .show();
        }

        private boolean addPermission(List<String> permissionsList, String permission) {
            if (getActivity().checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permission);
                if (!shouldShowRequestPermissionRationale(permission))
                    return false;
            }
            return true;
        }

        public void onDetach() {
            super.onDetach();
            count = 1;


            t.cancel();
            //timer was created at top of page as infinite, never cancelled even when the fragment closed -
            // t.cancel(): stops the timer and allows the page to switch without crashing
        }



    }
public void wifithing(){
            SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy");
            wifi.startScan();
            values.clear();

            try {
                netCount = netCount - 1;
                while (netCount >= 0) {
                    String currentDateTimeString = dateformat.getDateTimeInstance().format(new Date());
                    device d = new device();

                    d.setName(wifiList.get(netCount).SSID.toString()+"\n"+ wifiList.get(netCount).BSSID +" "+ wifiList.get(netCount).level +"\n" + currentDateTimeString );
                    //TempWifi = d;//returns nothing, need to make it return ssid

                    //TempWifi = "";// clears the old data
                    TempWifi = wifiList.get(netCount).SSID.toString(); //adds the new ssid
                    TempBSSID = wifiList.get(netCount).BSSID.toString(); //adds the new bssid
                    Templevel = Integer.toString(wifiList.get(netCount).level);// adds the new level

                    //currently have issue where one/two ssids are put in database
                    // maybe see how many "SSIDS" database recieves and how many show up on scan
                    // 20 on server, 20 on app
                    //20 on server, 20 on app
                    //19 on server, 19 on app

                    InsertData();// calls the method which sends the data to server

                    Log.d("WiFi",d.getName().toString());
                    values.add(d);
                    wifiScanAdapter.notifyDataSetChanged();
                    netCount=netCount -1;
                    }
                }
            catch (Exception e){
                Log.d("Wifi", e.getMessage());
                }

        }




        //this code is responsible for sending data to the server through PHP////////////////////////////////////////////////////////
        public void InsertData(){

            class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
                @Override
                protected String doInBackground(String... params) {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                    nameValuePairs.add(new BasicNameValuePair("SSID", TempWifi));
                    nameValuePairs.add(new BasicNameValuePair("MAC", TempBSSID));
                    nameValuePairs.add(new BasicNameValuePair("level", Templevel));


                    try {
                        HttpClient httpClient = new DefaultHttpClient();

                        HttpPost httpPost = new HttpPost(ServerURL);

                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        HttpResponse httpResponse = httpClient.execute(httpPost);

                        HttpEntity httpEntity = httpResponse.getEntity();


                    } catch (ClientProtocolException e) {

                    } catch (IOException e) {

                    }

                    return "Data Inserted Successfully";
                }

                @Override
                protected void onPostExecute(String result) {

                    super.onPostExecute(result);

                    //Toast.makeText(getContext(), TempWifi, Toast.LENGTH_SHORT).show();

                }
            }
            SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

            sendPostReqAsyncTask.execute();

        }///////////////////////////////////////////////////////////////////////////////////////////////////////////////
package com.example.joe.ratscanner;
导入android.Manifest;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.content.pm.PackageManager;
导入android.net.wifi.ScanResult;
导入android.net.wifi.WifiManager;
导入android.os.AsyncTask;
导入android.os.Build;
导入android.os.Bundle;
导入android.support.v4.app.Fragment;
导入android.support.v7.app.AlertDialog;
导入android.support.v7.widget.LinearLayoutManager;
导入android.support.v7.widget.RecyclerView;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.Button;
导入android.widget.Toast;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入java.io.IOException;
导入java.text.simpleDataFormat;
导入java.util.ArrayList;
导入java.util.Date;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入java.util.Timer;
导入java.util.TimerTask;
导入java.util.concurrent.Executor;
//返回充气机。充气(R.layout.fragment_wifi,容器,假);
/**
*一个简单的{@link Fragment}子类。
*/
公共类wififragment扩展了片段{
整数计数=0;
定时器t;
字符串ServerURL=”http://ratscanner.duckdns.org/get_data.php" ;
字符串TempWifi;
字符串TempBSSID;
字符串模板层;
串试验;
字符串正在发生;
TimerTask timer=新的TimerTask(){
@凌驾
公开募捐{
getActivity().runOnUiThread(新的Runnable()){
@凌驾
公开募捐{
//计数--;
//如果(计数>=0){
如果(计数=0){
//Toast.makeText(getActivity(),“this updated”,Toast.LENGTH_SHORT.show();
//wifithing();
//InsertData();//以后可能会删除它
}
}
});
//如果(计数=Build.VERSION\u CODES.M){
checkandAskPermission();
}否则{
wifithing();
}
btnScan.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
wifithing();
InsertData();
InsertData();
Toast.makeText(getContext(),netCount+“\n”+AnetCount,Toast.LENGTH\u SHORT).show();
}
});
}
/*公共空间装修(){
SimpleDataFormat dateformat=新的SimpleDataFormat(“dd MMM yyyy”);
wifi.startScan();
value.clear();
试一试{
净计数=净计数-1;
而(网络计数>=0){
字符串currentDateTimeString=dateformat.getDateTimeInstance().format(新日期());
设备d=新设备();
d、 setName(wifiList.get(netCount).SSID.toString()+“\n”+wifiList.get(netCount).BSSID+”“+wifiList.get(netCount).level+“\n”+currentDateTimeString);
//TempWifi=d;//不返回任何内容,需要使其返回ssid
//TempWifi=“;//清除旧数据
TempWifi=wifiList.get(netCount.SSID.toString();//添加新的SSID
TempBSSID=wifiList.get(netCount.BSSID.toString();//添加新的BSSID
Templevel=Integer.toString(wifiList.get(netCount.level);//添加新级别
//目前有