WiFi P2P是指通過(guò)WiFi直接連接兩臺(tái)設(shè)備之間的無(wú)線點(diǎn)對(duì)點(diǎn)通信,不需要通過(guò)路由器或者互聯(lián)網(wǎng)。這種技術(shù)被廣泛應(yīng)用于移動(dòng)設(shè)備之間的文件共享、游戲聯(lián)機(jī)、音樂(lè)播放等應(yīng)用場(chǎng)景中。
WiFi P2P的優(yōu)點(diǎn)在于可以在沒(méi)有網(wǎng)絡(luò)的情況下建立設(shè)備之間的連接,同時(shí)具有高速和低延遲的特點(diǎn)。它還支持多種語(yǔ)言編程接口,并且使用起來(lái)非常簡(jiǎn)單。
在Android中,WiFi P2P可以通過(guò)WifiP2pManager類進(jìn)行實(shí)現(xiàn),它提供了許多方法來(lái)掃描可用設(shè)備、建立P2P連接并傳輸數(shù)據(jù)等功能。開(kāi)發(fā)者可以通過(guò)這些方法來(lái)實(shí)現(xiàn)設(shè)備之間的文件傳輸?shù)炔僮鳌?/p>
WiFi和藍(lán)牙是兩種不同類型的無(wú)線通信技術(shù),在許多方面都有不同的特點(diǎn)和用途。
以下是一些常見(jiàn)的WiFi和藍(lán)牙的比較:
- 傳輸速率:WiFi傳輸速度更快,可以達(dá)到幾百兆比特每秒,而藍(lán)牙通常只能達(dá)到幾兆比特每秒。
- 距離限制:WiFi的覆蓋范圍通常更大,可以在較長(zhǎng)的距離內(nèi)進(jìn)行通信,而藍(lán)牙的覆蓋范圍通常比較小,僅能在短距離內(nèi)通信。
- 電池壽命:由于WiFi的功率更大,因此它通常消耗更多的電池生命,而藍(lán)牙通常需要更少的功率,因此它通常耗電更少。
下面是使用Wifi P2P傳輸文件的基本代碼示例,您可以根據(jù)需要進(jìn)行調(diào)整:
1. 添加權(quán)限和依賴項(xiàng)
在AndroidManifest.xml中添加以下權(quán)限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
在build.gradle文件中添加以下依賴項(xiàng):
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
2. 設(shè)置布局文件
在布局文件中添加以下代碼:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#000000" />
<Button
android:id="@+id/button_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="搜索可用設(shè)備" />
<ListView
android:id="@+id/list_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button_search"
android:layout_marginTop="20dp"
android:visibility="gone" />
</RelativeLayout>
3. 創(chuàng)建WifiP2pManager和WifiP2pManager.Channel對(duì)象
在Activity中定義以下變量:
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private BroadcastReceiver mReceiver;
private IntentFilter mIntentFilter;
private List<WifiP2pDevice> peers = new ArrayList<>();
private WifiP2pDeviceListAdapter mAdapter;
在Activity的onCreate()方法中,創(chuàng)建WifiP2pManager和WifiP2pManager.Channel對(duì)象:
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
4. 注冊(cè)廣播接收器
在Activity中創(chuàng)建以下BroadcastReceiver對(duì)象:
mReceiver = new WifiDirectBroadcastReceiver(mManager, mChannel, this);
WifiDirectBroadcastReceiver是一個(gè)自定義廣播接收器類,它負(fù)責(zé)處理與Wifi P2P相關(guān)的廣播事件。
在Activity的onResume()方法中,注冊(cè)廣播接收器:
registerReceiver(mReceiver, mIntentFilter);
在Activity的onPause()方法中,注銷廣播接收器:
unregisterReceiver(mReceiver);
5. 開(kāi)始搜索可用設(shè)備
通過(guò)調(diào)用startDiscovery()方法開(kāi)始搜索可用設(shè)備:
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
//搜索成功
}
@Override
public void onFailure(int reasonCode) {
//搜索失敗
}
});
6. 顯示可用設(shè)備列表
創(chuàng)建一個(gè)自定義適配器類WifiP2pDeviceListAdapter,用于顯示可用設(shè)備列表中的每個(gè)設(shè)備:
public class WifiP2pDeviceListAdapter extends ArrayAdapter<WifiP2pDevice> {
private List<WifiP2pDevice> items;
private Context ctx;
public WifiP2pDeviceListAdapter(Context context, int textViewResourceId,
List<WifiP2pDevice> objects) {
super(context, textViewResourceId, objects);
items = objects;
ctx = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row_devices, null);
}
WifiP2pDevice device = items.get(position);
if (device != null) {
TextView top = (TextView) v.findViewById(R.id.device_name);
TextView bottom = (TextView) v.findViewById(R.id.device_details);
if (top != null) {
top.setText(device.deviceName);
}
if (bottom != null) {
bottom.setText(getDeviceStatus(device.status));
}
}
return v;
}
private String getDeviceStatus(int deviceStatus) {
switch (deviceStatus) {
case WifiP2pDevice.AVAILABLE:
return "可用";
case WifiP2pDevice.INVITED:
return "已邀請(qǐng)";
case WifiP2pDevice.CONNECTED:
return "已連接";
case WifiP2pDevice.FAILED:
return "失敗";
case WifiP2pDevice.UNAVAILABLE:
return "不可用";
default:
return "未知狀態(tài)";
}
}
}
在Activity中,設(shè)置ListView的適配器:
mAdapter = new WifiP2pDeviceListAdapter(this, R.layout.row_devices, peers);
ListView listView = (ListView) findViewById(R.id.list_devices);
listView.setAdapter(mAdapter);
在BroadcaseReceiver接收到搜索結(jié)果后,在Activity中更新設(shè)備列表:
@Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
peers.clear();
peers.addAll(peerList.getDeviceList());
mAdapter.notifyDataSetChanged();
if (peers.size() == 0) {
//沒(méi)有可用設(shè)備
}
}
7. 連接到另一個(gè)設(shè)備
在設(shè)備列表中選擇一個(gè)設(shè)備,并調(diào)用connect()方法:
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
//連接成功
}
@Override
public void onFailure(int reason) {
//連接失敗
}
});
8. 傳輸文件
在連接成功后,使用WifiP2pGroup.getClientList()方法獲取已連接設(shè)備的列表,將文件傳輸?shù)搅斜碇械牡谝粋€(gè)設(shè)備:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-729087.html
WifiP2pGroup group = (WifiP2pGroup) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP);
if (group != null) {
Collection<WifiP2pClient> clients = group.getClientList();
if (clients.size() > 0) {
WifiP2pClient client = (WifiP2pClient) clients.toArray()[0];
File file = new File(filePath);
if (file.exists()) {
try {
FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = client.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//文件不存在
}
} else {
//沒(méi)有連接設(shè)備
}
} else {
//組不存在
}
注意:以上代碼僅用于演示如何使用Wifi P2P傳輸文件,您需要根據(jù)自己的情況進(jìn)行修改。此外,Wifi P2P傳輸文件的性能可能會(huì)受到網(wǎng)絡(luò)環(huán)境的影響,并不適用于大文件傳輸。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-729087.html
到了這里,關(guān)于Android WiFi P2P數(shù)據(jù)傳輸?shù)奈恼戮徒榻B完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!