获取所有可用的wi-fi信息并发送到mysql数据库

wrrgggsh  于 2021-06-25  发布在  Mysql
关注(0)|答案(0)|浏览(234)

我对java相当陌生,但我正在尝试创建一个应用程序,定期收集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
        }

    }

在wififragment.java的代码片段之前

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();

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题