close

MainActivity這是最基本的網路連線操作,包括了wifi 的scan,連線,開啟,關閉。
本以為這是一個最基本且簡單的需求,没想到也是花費了一段時間研究程式
Wifi scan 程式流程要解決下面的需求

資料來源:
https://www.includehelp.com/code-snippets/android-application-to-display-available-wifi-network-and-connect-with-specific-network.aspx
https://www.nplix.com/scan-list-wifi-network-android/
https://www.nplix.com/scan-wifi-network-connect-android/
http://cooking-java.blogspot.com/2010/07/android-wifi.html
https://bryceknowhow.blogspot.com/2014/02/android-wifimanagerget-wifissid-power.html
http://fecbob.pixnet.net/blog/post/39322597-android-%3E-wifi-%3E-%E6%8E%83%E6%8F%8F%E9%99%84%E8%BF%91wifi-
https://www.tutorialspoint.com/android/android_wi_fi.htm
https://codertw.com/android-%E9%96%8B%E7%99%BC/339828/ (自動連線)
https://codertw.com/android-%E9%96%8B%E7%99%BC/330593/ (自動連線)
http://king39461.pixnet.net/blog/post/349470859-android-wifi-connection(連線)
http://fecbob.pixnet.net/blog/post/39248623-android-wifi%E9%80%A3%E6%8E%A5%E9%96%8B%E7%99%BC
http://fecbob.pixnet.net/blog/post/39278785-android-%E8%87%AA%E5%8B%95%E9%80%A3%E6%8E%A5%E6%8C%87%E5%AE%9Assid%E7%9A%84wifi%E7%86%B1%E9%BB%9E%EF%BC%88%E4%B8%8D%E5%8A%A0%E5%AF%86-%E5%8A%A0
https://stackoverflow.com/questions/15225232/programmatically-connect-to-an-android-device-in-portable-hotspot
https://www.nplix.com/scan-wifi-network-connect-android/ (good)
https://forums.xamarin.com/discussion/5402/connect-to-wifi-networks-programmatically
https://stackoverflow.com/questions/8818290/how-do-i-connect-to-a-specific-wi-fi-network-in-android-programmatically(good)

這是網路程式,但是有問題,僅供參考: 
(1)MainActivity.java 
package tw.nicky.WifiManagerExample;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
 private WifiManager wiFiManager;
 ListView lv;
 TextView textStatus;
 Button buttonScan;
 int size = 0;
 List results;
 ArrayList> arraylist = new ArrayList>();
 SimpleAdapter adapter;
 private Button turnOnWifiButn;
 private Button turnOffWifiButn;
 
private static final Map wifichannel = new HashMap();
  static{
   wifichannel.put("2412", "2.4G Ch01");wifichannel.put("2417", "2.4G Ch02");
   wifichannel.put("2422", "2.4G Ch03");wifichannel.put("2427", "2.4G Ch04");
   wifichannel.put("2432", "2.4G Ch05");wifichannel.put("2437", "2.4G Ch06");
   wifichannel.put("2442", "2.4G Ch07");wifichannel.put("2447", "2.4G Ch08");
   wifichannel.put("2452", "2.4G Ch09");wifichannel.put("2457", "2.4G Ch10");
   wifichannel.put("2462", "2.4G Ch11");wifichannel.put("2467", "2.4G Ch12");
   wifichannel.put("2472", "2.4G Ch13");wifichannel.put("2484", "2.4G Ch14");
  }

 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
   textStatus = (TextView) findViewById(R.id.textView2);
  buttonScan = (Button) findViewById(R.id.button1);
  lv = (ListView) findViewById(R.id.listView1);

 // 取得WifiManager
 wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
// 一個 dialog 判別是否有連線,否則顯示出連線dialog
 if(wifi.isWifiEnabled()==false) 
 { 
   AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
   dialog.setTitle("Remind"); 
   dialog.setMessage("Your Wi-Fi is not enabled, enable?"); 
   dialog.setIcon(android.R.drawable.ic_dialog_info); 
   dialog.setCancelable(false); 
   dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
       @Override public void onClick(DialogInterface dialog, int which) { 
        // TODO Auto-generated method stub 
          wifi.setWifiEnabled(true); 
          Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); 
      } }); 
    dialog.show();
 }
 //然後按下Start Scan的按鈕開始搜尋附近的Wi-Fi網路 
  this.adapter = new SimpleAdapter(MainActivity.this, arraylist, R.layout.list, new String[] {"ssid","power","freq"}, new int[] {R.id.ssid, R.id.power, R.id.freq}); 
  lv.setAdapter(adapter); 
 registerReceiver(new BroadcastReceiver() { 
      @Override public void onReceive(Context context, Intent intent) { 
         // TODO Auto-generated method stub results = wifi.getScanResults(); size = results.size(); 
      }
 }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); 
 buttonScan.setOnClickListener(new OnClickListener() {}
    @Override
    public void onClick(View v) {
      // TODO Auto-generated method stub
        arraylist.clear();
        wifi.startScan();
                
        Toast.makeText(MainActivity.this, "Scanning..."+size, Toast.LENGTH_LONG).show();
        try {
          size = size -1;
          while(size >= 0)
          {
            HashMap item = new HashMap();
            item.put("ssid", results.get(size).SSID);
            item.put("power", new String(results.get(size).level+" dBm"));
            String wifichn = wifichannel.containsKey(new String(""+results.get(size).frequency))? wifichannel.get(new String(""+results.get(size).frequency)):"5G";
            item.put("freq", wifichn);
            arraylist.add(item);
            size--;
            adapter.notifyDataSetChanged();
          }
          Collections.sort(arraylist, new Comparator>() {

           @Override
           public int compare(HashMap lhs, HashMap rhs) {
              // TODO Auto-generated method stub
              return ((String) lhs.get("power")).compareTo((String) rhs.get("power"));
           }
          });
          textStatus.setText(arraylist.get(0).get("ssid"));
        } catch (Exception e) {
          // TODO: handle exception
        }
      }
    });
   }

  

 // 兩個button 
  
  turnOnWifiButn = (Button) findViewById(R.id.turnOnWifiButn);
  turnOffWifiButn = (Button) findViewById(R.id.turnOffWifiButn);

  // 開啟wifi
  turnOnWifiButn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    //若wifi狀態為關閉則將它開啟
    if (!wiFiManager.isWifiEnabled()) {
     wiFiManager.setWifiEnabled(true);
    }
   }
  });

  // 關閉wifi
  turnOffWifiButn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    //若wifi狀態為開啟則將它關閉
    if (wiFiManager.isWifiEnabled()) {
     wiFiManager.setWifiEnabled(false);
    }
   }
  });
 }
}


3. activity_main.xml (Layout)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button 
android:text="開啟Wifi" 
android:id="@+id/turnOnWifiButn" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>

<Button 
android:text="關閉Wifi" 
android:id="@+id/turnOffWifiButn" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</Button>
</LinearLayout>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="46dp"
        android:background="#ff8" >
    </ListView>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/wifi_ssid" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/listView1"
        android:layout_below="@+id/button1"
        android:text="@string/wifi_analysis" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView1"
        android:text="@string/start_scan" />

</RelativeLayout>

list.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/ssid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/power"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/ssid"
        android:layout_below="@+id/ssid"
        android:text="TextView" />

    <TextView
        android:id="@+id/freq"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/power"
        android:layout_alignBottom="@+id/power"
        android:layout_centerHorizontal="true"
        android:text="TextView" />

</RelativeLayout>

4. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tw.nicky.WifiManagerExample"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".WifiManagerExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
</manifest> 

以上程式焆未完成測試,所以還没貼上畫面,僅先記錄別人的寫法。

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 stanley 的頭像
    stanley

    史坦利Stanley程式Maker的部落格

    stanley 發表在 痞客邦 留言(0) 人氣()