-1

这部分代码显示了可能的 wifi 连接。问题是它都在一个独特的文本视图中。是否可以从此代码创建 wifi 连接的列表视图?

package com.pkg.androidmemoryinfo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;
import java.util.List;

    public class MainActivity extends Activity implements OnClickListener {

        private String ips = null;
        private WifiManager wifi;
        private WifiInfo info;
        private TextView ipv;
        private TextView text;

        TextView mainText;
        WifiManager mainWifi;
        WifiReceiver receiverWifi;
        List<ScanResult> wifiList;
        StringBuilder sb = new StringBuilder();

        static final int TIME_DIALOG_ID = 1111;
        private TextView output;
        public Button btnClick;

        private int hour;
        private int minute;
        private ListView lv;
        public ArrayAdapter<String> adapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // Nav Drawer //

            // fine //

            mainText = (TextView) findViewById(R.id.mainText);

            // Initiate wifi service manager
            mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

            // Check for wifi is disabled
            if (mainWifi.isWifiEnabled() == false)
                 {   
                     // If wifi disabled then enable it
                     Toast.makeText(getApplicationContext(), "Il Wifi è disattivato.. Accensione in corso.", 
                     Toast.LENGTH_LONG).show();

                     mainWifi.setWifiEnabled(true);
                 } 

            // wifi scaned value broadcast receiver 
            receiverWifi = new WifiReceiver();

            // Register broadcast receiver 
            // Broacast receiver will automatically call when number of wifi connections changed
            registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            mainWifi.startScan();
            mainText.setText("Ricerca reti Wi-Fi in corso...");

            /// Wifi Info ///
            wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); // istanzio l'oggetto wifi(classe WifiManager)
            info = wifi.getConnectionInfo(); // istanzio l'oggetto info(classe WifiInfo)


            if (info.getBSSID() != null) { // verifico che la connessione si attiva, in particolare il metodo getBSSID() restituisce valore nullo se la connessione non è attiva
                this.ipv = (TextView)this.findViewById(R.id.addres);
                this.text = (TextView)this.findViewById(R.id.text);
                this.text.setText("Dispositivo connesso a " + info.getSSID()); //qui viene richiamato il metodo getSSID() che restituisce una stringa, in particolare l'identificativo dell'SSID 
                //int ip = info.getIpAddress(); // il metodo getIpAddress() restituisce un intero che rappresenta l'indirizzo IP, ovviamente non è la tipica rappresentazione a cui siamo abituati ex.: 127.0.0.1
                //this.ips = ((( ip & 0xFF )) + "." + (( ip >> 8 ) & 0xFF ) + "." + (( ip >> 16 ) & 0xFF ) + "." + (( ip >> 24 ) & 0xFF ));// converto l'intero nella tipica notazione, ho adottato questo sistema un po grezzo poiche non conosco un altro metodo piu semplice
                this.ipv.setText(ips);
            } else {// se la connessione non è attiva 
                this.ipv = (TextView)this.findViewById(R.id.addres);
                this.ipv.setText("Nessuna connessione Wifi attiva!");
            }
            //// FINE /////
            output = (TextView) findViewById(R.id.output);

            /********* display current time on screen Start ********/

               final Calendar c = Calendar.getInstance();
               // Current Hour
               hour = c.get(Calendar.HOUR_OF_DAY);
               // Current Minute
               minute = c.get(Calendar.MINUTE);

               // Append in a StringBuilder
               StringBuilder outputMsg = new StringBuilder().append(utilTime(hour)).append(":")
               .append(utilTime(minute));

               // set current time into output textview
               output.setText(outputMsg);

            /********* display current time on screen End ********/

               // Add Button Click Listener
               addButtonClickListener();  

        }


        public boolean onCreateOptionsMenu(Menu menu) {
            menu.add(0, 0, 0, "Refresh");
            return super.onCreateOptionsMenu(menu);
        }

        public boolean onMenuItemSelected(int featureId, MenuItem item) {
            mainWifi.startScan();
            mainText.setText("Inizio Ricerca");
            return super.onMenuItemSelected(featureId, item);
        }

        protected void onPause() {
            unregisterReceiver(receiverWifi);
            super.onPause();
        }

        protected void onResume() {
            registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            super.onResume();
        }

        // Broadcast receiver class called its receive method 
        // when number of wifi connections changed

        class WifiReceiver extends BroadcastReceiver {

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

                sb = new StringBuilder();
                wifiList = mainWifi.getScanResults(); 
                sb.append("\n Connessioni trovate :"+wifiList.size()+"\n\n");

                adapter = new ArrayAdapter<String>(getAppContext(),R.layout.activity_main); //xml file see below...
                for(int i = 0; i < wifiList.size(); i++){
                     adapter.add(" "+new Integer(i+1).toString() + ". "+ (wifiList.get(i)).toString());
                }
                lv.setAdapter(adapter);

                mainText.setText(sb);  
            }

            private Context getAppContext() {
                // TODO Auto-generated method stub
                return null;
            }

        }

       ////// DIALOG TIMEPICKER //////// 
        public void addButtonClickListener() {

            btnClick = (Button) findViewById(R.id.btnClick);

            btnClick.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    showDialog(TIME_DIALOG_ID);

                }

            });

        }


        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case TIME_DIALOG_ID:

                // set time picker as current time
                return new TimePickerDialog(this, timePickerListener, hour, minute,
                        false);

            }
            return null;
        }

        private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {


            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
                // TODO Auto-generated method stub
                hour   = hourOfDay;
                minute = minutes;

                // set current time into output textview
                output.setText(new StringBuilder().append(utilTime(hour))
                        .append(":").append(utilTime(minute)));
             }

        };

        private static String utilTime(int value) {

            if (value < 10)
                return "0" + String.valueOf(value);
            else
                return String.valueOf(value);
        }


        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }
    }

或者任何人都有带有 wifi 连接的列表视图?

4

1 回答 1

0

变量:

private ListView lv;
public ArrayAdapter<String> adapter;

代码:

...
adapter = new ArrayAdapter<String>(getAppContext(),R.layout.listitem); //xml file see below...
for(int i = 0; i < wifiList.size(); i++){
     adapter.add(" "+new Integer(i+1).toString() + ". "+ (wifiList.get(i)).toString());
}
lv.setAdapter(adapter);

listitem.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listitem_intervals"
    android:layout_width="match_parent"
     <!-- //font attributes you want to use in the listView -->
/>

*查看“getAppContext()”方法的注释

于 2013-06-20T23:03:09.290 回答