2015-05-23 31 views
-1

我是Android編程的新手,我正在研究能夠使用手機打開電腦的項目。我已經寫了我的代碼,當單擊列表視圖中的項目時,它將獲取mac地址並使用它來打開計算機。問題是,數據包永遠不會發送,我正在使用模擬器。我試圖在谷歌搜索解決方案,但無法找到足夠的突破。真的需要你的幫助。如何在Android中使用手機以編程方式打開電腦

這裏是我的代碼:

package black.cheetah.blackcheetah; 


import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 

import android.os.Bundle; 
import android.os.StrictMode; 
import android.app.Activity; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Toast; 

public class ComputerTurnOnList extends Activity { 
public static final int PORT = 9; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_computer_turn_on_list); 
if (android.os.Build.VERSION.SDK_INT > 8) { 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll() 
      .build(); 
    StrictMode.setThreadPolicy(policy); 
} 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. 
getMenuInflater().inflate(R.menu.main, menu); 
return true; 
} 

public void buttonClick(View view) { 
String broadcastIP = "192-168-43-171"; 
String mac = "3C-97-0E-82-3D-BD"; 
Log.d("Read mac= ", mac); 
Log.d("Read ip=", broadcastIP); 
ComputerTurnOnList.wakeup(broadcastIP, mac); 
    } 


private static byte[] getMacBytes(String mac) throws IllegalArgumentException { 
    Log.d("GetMacBytes", "method started"); 
// TODO Auto-generated method stub 
    byte[] bytes = new byte[6]; 
     String[] hex = mac.split("(\\:|\\-)"); 
     if (hex.length != 6) { 
      throw new IllegalArgumentException("Invalid MAC address."); 
     } 
     try { 
      for (int i = 0; i < 6; i++) { 
       bytes[i] = (byte) Integer.parseInt(hex[i], 16); 
       Log.d("GetMacbytes", "calculated"); 
       Log.d("GetMacBytes (bytes)", new String(bytes)); 
      } 
     } 
     catch (NumberFormatException e) { 
      Log.e("GetMacBytes","error"); 
     } 
     return bytes; 
} 


public static void wakeup(String broadcastIP, String mac) { 
    Log.d("wakeup", "method started"); 
if (mac == null) { 
    Log.d("Mac error at wakeup", "mac = null"); 
    return; 
} 

    try { 
     byte[] macBytes = getMacBytes(mac); 
     Log.d("wakeup (bytes)", new String(macBytes)); 
     byte[] bytes = new byte[6 + 16 * macBytes.length]; 
     for (int i = 0; i < 6; i++) { 
      bytes[i] = (byte) 0xff; 
     } 
     for (int i = 6; i < bytes.length; i += macBytes.length) { 
      System.arraycopy(macBytes, 0, bytes, i, macBytes.length); 
     } 

     Log.d("wakeup", "calculating completed, sending..."); 
     InetAddress address = InetAddress.getByName(broadcastIP); 
     DatagramPacket packet = new DatagramPacket(bytes, bytes.length,address,9); 
     DatagramSocket socket = new DatagramSocket(); 
     socket.send(packet); 
     socket.close(); 
Toast.makeText(null, "Time up! Couldn't find Computer", Toast.LENGTH_SHORT).show(); 
     Log.d("wakeup", "Magic Packet sent"); 
     } 
     catch (Exception e) { 
      Log.e("wakeup", "error" + e.getMessage()); 
    } 

} 

} 

當我跑到這裏來是一個錯誤:

05-30 06:26:15.607: D/Read mac=(1755): XX-XX-XX-XX-XX-XX 
05-30 06:26:15.617: D/Read ip=(1755): xxx-xxx-xx-xxx 
05-30 06:26:15.617: D/wakeup(1755): method started 
05-30 06:26:15.617: D/GetMacBytes(1755): method started 
05-30 06:26:15.617: D/GetMacbytes(1755): calculated 
05-30 06:26:15.617: D/GetMacBytes (bytes)(1755): <���������� 
05-30 06:26:15.617: D/GetMacbytes(1755): calculated 
05-30 06:26:15.657: D/GetMacBytes (bytes)(1755): <��������� 
05-30 06:26:15.657: D/GetMacbytes(1755): calculated 
05-30 06:26:15.657: D/GetMacBytes (bytes)(1755): <������� 
05-30 06:26:15.667: D/GetMacbytes(1755): calculated 
05-30 06:26:15.667: D/GetMacBytes (bytes)(1755): <������ 
05-30 06:26:15.667: D/GetMacbytes(1755): calculated 
05-30 06:26:15.667: D/GetMacBytes (bytes)(1755): <��=�� 
05-30 06:26:15.667: D/GetMacbytes(1755): calculated 
05-30 06:26:15.667: D/GetMacBytes (bytes)(1755): <��=� 
05-30 06:26:15.667: D/wakeup (bytes)(1755): <��=� 
05-30 06:26:15.667: D/wakeup(1755): calculating completed, sending... 
05-30 06:26:15.667: E/wakeup(1755): errorUnable to resolve host "xxx-xxx-xx-xxx": No address associated with hostname 
+0

仿真器從本地網絡隔離並擁有自己的地址空間中的活動工作。檢查此:https://developer.android.com/tools/devices/emulator.html#emulatornetworking –

+0

我試圖再次運行它,它給了我android.os.networkonmainthreadexception –

+0

你不能做的網絡操作UI線程。你必須使用'AsyncTask':https://developer.android.com/training/articles/perf-anr.html#Aviiding –

回答

1

我不認爲你可以通過模擬器發送UDP或至少它不是簡單。在您的真實設備上嘗試一下。

我得到了它這個

public class WakeOnLAN { 

    public static final int DEFAULT_PORT = 9; 

    private static final String TAG = WakeOnLAN.class.getSimpleName(); 
    private static final String MAC_REGEX = "([0-9a-fA-F]{2}[-:]){5}[0-9a-fA-F]{2}"; 

    public static int sendPacket(String ipStr, String macStr) { 
     return sendPacket(ipStr, macStr, DEFAULT_PORT); 
    } 

    public static int sendPacket(String ipStr, String macStr, int port) throws IllegalArgumentException { 
     if (port < 0 || port > 65535) { 
      throw new IllegalArgumentException("Port must be in the range [0, 65535]. Magic packet is usually used on port 7 or 9"); 
     } 

     byte[] macBytes = getMacBytes(macStr); 
     byte[] bytes = new byte[6 + 16 * macBytes.length]; 

     try { 
      for (int i = 0; i < 6; i++) { 
       bytes[i] = (byte) 0xff; 
      } 
      for (int i = 6; i < bytes.length; i += macBytes.length) { 
       System.arraycopy(macBytes, 0, bytes, i, macBytes.length); 
      } 

      InetAddress address = InetAddress.getByName(ipStr); 
      DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port); 
      DatagramSocket socket = new DatagramSocket(); 
      socket.send(packet); 
      socket.close(); 

      Log.d(TAG, "Wake-on-LAN packet sent."); 

      return 0; 
     } catch (Exception e) { 
      Log.e(TAG, "Failed to send Wake-on-LAN packet:" + e); 
      return -1; 
     } 
    } 

    private static byte[] getMacBytes(String macStr) throws IllegalArgumentException { 

     if (!macStr.matches(MAC_REGEX)) { 
      throw new IllegalArgumentException("Invalid MAC address"); 
     } 

     byte[] bytes = new byte[6]; 
     String[] hex = macStr.split("(:|\\-)"); 

     try { 
      for (int i = 0; i < 6; i++) { 
       bytes[i] = (byte) Integer.parseInt(hex[i], 16); 
      } 
     } catch (NumberFormatException e) { 
      // Should not happen, the regex forbids it, but it doesn't compile otherwise. 
      throw new IllegalArgumentException("Invalid hex digit in MAC address."); 
     } 
     return bytes; 
    } 
} 

而且

public class WakeOnLanActivity extends AppCompatActivity implements View.OnClickListener { 


    private static final String TEST_IP = "192.168.1.255"; 
    private static final String MAC = "74:D4:35:E7:BA:DC"; 

    private Button btnSend; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.wake_on_lan_demo); 
     setWidgetConnections(); 
    } 

    private void setWidgetConnections() { 
     btnSend = (Button) findViewById(R.id.btnSend); 
     btnSend.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       new WakeOnLanTask(TEST_IP, MAC, 9).execute(); 
      } 
     }); 
    } 


    class WakeOnLanTask extends AsyncTask<Void, Void, Integer> { 

     private String IP; 
     private String MAC; 
     private int port; 

     public WakeOnLanTask(String ip, String mac, int port) { 
      this.IP = ip; 
      this.MAC = mac; 
      this.port = port; 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
     } 

     @Override 
     protected Integer doInBackground(Void... args) { 
      return WakeOnLAN.sendPacket(IP, MAC, port); 
     } 

     @Override 
     protected void onPostExecute(Integer integer) { 
      super.onPostExecute(integer); 
     } 
    } 

    @Override 
    public void onClick(View view) { 
    } 

} 
+0

謝謝我試試 –

+0

仍然沒有奏效。代碼是否正確? –

+0

@CondradMariki我不知道你的代碼,但我把它放在這裏。我確信這一個作品。 –

相關問題