server side - Transfer Data between Android devices using wifi direct? -
i have implement wifi direct project,my aim pass string value between 2 wifidirect connected devices when of app condition satisfies.right have listed peers , made connection between selected peer.what idea pass json file between devices.so before try execute idea try pass image file between 2 devices.i followed steps android wifidirect tutorial.listing peers , connection between peers success full cant pass data between devices.the follwing code. filetransferservice.java
package jing.app.directwifi; import android.app.intentservice; import android.content.contentresolver; import android.content.context; import android.content.intent; import android.net.uri; import android.util.log; import java.io.filenotfoundexception; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.net.inetsocketaddress; import java.net.socket; /** * service process each file transfer request i.e intent opening * socket connection wifi direct group owner , writing file */ public class filetransferservice extends intentservice { private static final int socket_timeout = 5000; public static final string action_send_file = "jing.app.directwifi.send_file"; public static final string extras_file_path = "file_url"; public static final string extras_group_owner_address = "go_host"; public static final string extras_group_owner_port = "go_port"; public filetransferservice(string name) { super(name); } public filetransferservice() { super("filetransferservice"); } /* * (non-javadoc) * @see android.app.intentservice#onhandleintent(android.content.intent) */ @override protected void onhandleintent(intent intent) { context context = getapplicationcontext(); if (intent.getaction().equals(action_send_file)) { string fileuri = intent.getextras().getstring(extras_file_path); string host = intent.getextras().getstring(extras_group_owner_address); socket socket = new socket(); int port = intent.getextras().getint(extras_group_owner_port); try { // log.d(wifidirectactivity.tag, "opening client socket - "); socket.bind(null); socket.connect((new inetsocketaddress(host, port)), socket_timeout); log.d("connected", "client socket - " + socket.isconnected()); outputstream stream = socket.getoutputstream(); contentresolver cr = context.getcontentresolver(); inputstream = null; try { = cr.openinputstream(uri.parse(fileuri)); } catch (filenotfoundexception e) { log.d("exp", e.tostring()); } mainactivity.copyfile(is, stream); log.d("exp" ,"client: data written"); } catch (ioexception e) { log.e("exp", e.getmessage()); } { if (socket != null) { if (socket.isconnected()) { try { socket.close(); } catch (ioexception e) { // give e.printstacktrace(); } } } } } } }
main activity.java
package jing.app.directwifi; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.net.serversocket; import java.net.socket; import java.util.arraylist; import java.util.collection; import android.app.activity; import android.app.alertdialog; import android.app.dialog; import android.app.dialogfragment; import android.content.broadcastreceiver; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.content.intentfilter; import android.net.uri; import android.net.wifi.wifiinfo; import android.net.wifi.wifimanager; import android.net.wifi.p2p.wifip2pconfig; import android.net.wifi.p2p.wifip2pdevice; import android.net.wifi.p2p.wifip2pdevicelist; import android.net.wifi.p2p.wifip2pinfo; import android.net.wifi.p2p.wifip2pmanager; import android.net.wifi.p2p.wifip2pmanager.actionlistener; import android.net.wifi.p2p.wifip2pmanager.channel; import android.net.wifi.p2p.wifip2pmanager.connectioninfolistener; import android.net.wifi.p2p.wifip2pmanager.peerlistlistener; import android.os.asynctask; import android.os.bundle; import android.os.environment; import android.provider.settings; import android.util.log; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.arrayadapter; import android.widget.button; import android.widget.textview; import android.widget.toast; public class mainactivity extends activity implements onclicklistener, android.content.dialoginterface.onclicklistener, connectioninfolistener { private wifip2pmanager mmanager; private channel mchannel; private broadcastreceiver mreceiver; private intentfilter mintentfilter; private button mdiscover; private textview mdevices; public arrayadapter madapter; private arraylist<wifip2pdevice> mdevicelist = new arraylist<wifip2pdevice>(); protected static final int choose_file_result_code = 20; int flag=0; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mdiscover = (button) findviewbyid(r.id.discover); mdiscover.setonclicklistener(this); mdevices = (textview) findviewbyid(r.id.peers); mmanager = (wifip2pmanager) getsystemservice(context.wifi_p2p_service); mchannel = mmanager.initialize(this, getmainlooper(), null); mreceiver = new wifidirectreceiver(mmanager, mchannel, this); mintentfilter = new intentfilter(); mintentfilter.addaction(wifip2pmanager.wifi_p2p_state_changed_action); mintentfilter.addaction(wifip2pmanager.wifi_p2p_peers_changed_action); mintentfilter.addaction(wifip2pmanager.wifi_p2p_connection_changed_action); mintentfilter.addaction(wifip2pmanager.wifi_p2p_this_device_changed_action); } @override protected void onresume() { super.onresume(); registerreceiver(mreceiver, mintentfilter); } @override protected void onpause() { super.onpause(); unregisterreceiver(mreceiver); } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.activity_main, menu); return true; } private class wifidirectreceiver extends broadcastreceiver { private wifip2pmanager mmanager; private channel mchannel; private mainactivity mactivity; public wifidirectreceiver(wifip2pmanager manager, channel channel, mainactivity activity) { super(); mmanager = manager; mchannel = channel; mactivity = activity; } @override public void onreceive(context context, intent intent) { string action = intent.getaction(); if (wifip2pmanager.wifi_p2p_state_changed_action.equals(action)) { int state = intent.getintextra(wifip2pmanager.extra_wifi_state, -1); if (state == wifip2pmanager.wifi_p2p_state_enabled) { string title = "android_id[" + getandroid_id() + "]"; title += " mac[" + getmacaddress() + "]"; toast.maketext(mactivity, "wi-fi direct enabled."+title, toast.length_short).show(); } else { toast.maketext(mactivity, "wi-fi direct disabled.", toast.length_short).show(); } } else if (wifip2pmanager.wifi_p2p_peers_changed_action.equals(action)) { if (mmanager != null) { mmanager.requestpeers(mchannel, new peerlistlistener() { @override public void onpeersavailable(wifip2pdevicelist peers) { if (peers != null) { mdevicelist.addall(peers.getdevicelist()); arraylist<string> devicenames = new arraylist<string>(); (wifip2pdevice device : mdevicelist) { devicenames.add(device.devicename); } if (devicenames.size() > 0) { madapter = new arrayadapter<string>(mactivity, android.r.layout.simple_list_item_1, devicenames); if(flag==0) { flag=1; showdevicelistdialog(); } } else { toast.maketext(mactivity, "device list empty.", toast.length_short).show(); } } } }); } } else if (wifip2pmanager.wifi_p2p_connection_changed_action.equals(action)) { } else if (wifip2pmanager.wifi_p2p_this_device_changed_action.equals(action)) { } } } @override public void onclick(view v) { switch (v.getid()) { case r.id.discover: ondiscover(); break; } } private void ondiscover() { mmanager.discoverpeers(mchannel, new actionlistener() { @override public void onsuccess() { toast.maketext(mainactivity.this, "discover peers successfully.", toast.length_short).show(); } @override public void onfailure(int reason) { toast.maketext(mainactivity.this, "discover peers failed.", toast.length_short).show(); } }); } private void showdevicelistdialog() { devicelistdialog devicelistdialog = new devicelistdialog(); devicelistdialog.show(getfragmentmanager(), "devices"); } private class devicelistdialog extends dialogfragment { @override public dialog oncreatedialog(bundle savedinstancestate) { alertdialog.builder builder = new alertdialog.builder(getactivity()); builder.settitle("select device") .setsinglechoiceitems(madapter, 0, mainactivity.this) .setnegativebutton("cancel", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { dialog.dismiss(); } }); return builder.create(); } } @override public void onclick(dialoginterface dialog, int which) { ondeviceselected(which); dialog.dismiss(); } private void ondeviceselected(int which) { wifip2pdevice device = mdevicelist.get(which); if (device == null) { return; } wifip2pconfig config = new wifip2pconfig(); config.deviceaddress = device.deviceaddress; mmanager.connect(mchannel, config, new actionlistener() { @override public void onsuccess() { toast.maketext(mainactivity.this, "connected", toast.length_short).show(); intent intent = new intent(intent.action_get_content); intent.settype("image/*"); startactivityforresult(intent, choose_file_result_code); } @override public void onfailure(int reason) { toast.maketext(mainactivity.this, "failed connect", toast.length_short).show(); } }); } /** * android_id */ private string getandroid_id() { return settings.secure.getstring(getcontentresolver(), settings.secure.android_id); } /** * wi-fi mac */ private string getmacaddress() { wifimanager manager = (wifimanager) getsystemservice(context.wifi_service); wifiinfo wifiinfo = manager.getconnectioninfo(); string mac = wifiinfo.getmacaddress(); // after group negotiation, assign group owner file // server. file server single threaded, single connection server // socket. new fileserverasynctask(getapplicationcontext()) .execute(); return mac; } @override public void onactivityresult(int requestcode, int resultcode, intent data) { // user has picked image. transfer group owner i.e peer using // filetransferservice. uri uri = data.getdata(); log.d("intent", "intent----------- " + uri); intent serviceintent = new intent(mainactivity.this, filetransferservice.class); serviceintent.setaction(filetransferservice.action_send_file); serviceintent.putextra(filetransferservice.extras_file_path, uri.tostring()); serviceintent.putextra(filetransferservice.extras_group_owner_address, getmacaddress()); serviceintent.putextra(filetransferservice.extras_group_owner_port, 8988); startservice(serviceintent); } /** * simple server socket accepts connection , writes data on * stream. */ public static class fileserverasynctask extends asynctask<void, void, string> { private context context; /** * @param context * @param statustext */ public fileserverasynctask(context context) { this.context = context; } @override protected string doinbackground(void... params) { try { system.out.println("insideeeeeeeeeeeeeeeeeeeeeeee"); serversocket serversocket = new serversocket(8988); log.d("server: socket opened", "server: socket opened"); socket client = serversocket.accept(); log.d("server: connection done", "server: connection done"); final file f = new file(environment.getexternalstoragedirectory() + "/" + context.getpackagename() + "/wifip2pshared-" + system.currenttimemillis() + ".jpg"); file dirs = new file(f.getparent()); if (!dirs.exists()) dirs.mkdirs(); f.createnewfile(); log.d("server: copying files ", "server: copying files " + f.tostring()); inputstream inputstream = client.getinputstream(); copyfile(inputstream, new fileoutputstream(f)); serversocket.close(); return f.getabsolutepath(); } catch (ioexception e) { log.e("exp", e.getmessage()); system.out.println(":iooo:"+e); return null; } } /* * (non-javadoc) * @see android.os.asynctask#onpostexecute(java.lang.object) */ @override protected void onpostexecute(string result) { if (result != null) { intent intent = new intent(); intent.setaction(android.content.intent.action_view); intent.setdataandtype(uri.parse("file://" + result), "image/*"); context.startactivity(intent); } } /* * (non-javadoc) * @see android.os.asynctask#onpreexecute() */ @override protected void onpreexecute() { } } public static boolean copyfile(inputstream inputstream, outputstream out) { byte buf[] = new byte[1024]; int len; long starttime=system.currenttimemillis(); try { while ((len = inputstream.read(buf)) != -1) { out.write(buf, 0, len); } out.close(); inputstream.close(); long endtime=system.currenttimemillis()-starttime; log.v("","time taken transfer bytes : "+endtime); } catch (ioexception e) { log.d("exp", e.tostring()); return false; } return true; } @override public void onconnectioninfoavailable(wifip2pinfo info) { // todo auto-generated method stub toast.maketext(getapplicationcontext(), "connectioninfoo", 3000).show(); } }
manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="jing.app.directwifi" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="14" android:targetsdkversion="16" /> <uses-permission android:name="android.permission.access_wifi_state" /> <uses-permission android:name="android.permission.change_wifi_state" /> <uses-permission android:name="android.permission.change_network_state" /> <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.access_network_state" /> <uses-permission android:name="android.permission.read_phone_state" /> <uses-permission android:name="android.permission.write_external_storage" /> <!-- market filtering --> <uses-feature android:name="android.hardware.wifi.direct" android:required="true" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="jing.app.directwifi.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <!-- used transferring files after successful connection --> <service android:name=".filetransferservice" android:enabled="true" /> </application> </manifest>
these files used in code .form tutorial have found
new fileserverasynctask(getapplicationcontext()) .execute();
where the incomming data begin accepted when need execute asyn thread,so me in portion have made mistake.how can transfer file between devices .
the android code demo wifi direct project able pass file unidirectional. ie. can send file client server only. need furthur modifications make work in both direction.
edit 2:
for need know ip address of both connected peers. use following function made following various sources modifications wherever appropriate.
public static string getipaddress() { try { list<networkinterface> interfaces = collections .list(networkinterface.getnetworkinterfaces()); /* * (networkinterface networkinterface : interfaces) { log.v(tag, * "interface name " + networkinterface.getname() + "mac = " + * getmacaddress(networkinterface.getname())); } */ (networkinterface intf : interfaces) { if (!getmacaddress(intf.getname()).equalsignorecase( globals.thisdeviceaddress)) { // log.v(tag, "ignore interface " + intf.getname()); // continue; } if (!intf.getname().contains("p2p")) continue; log.v(tag, intf.getname() + " " + getmacaddress(intf.getname())); list<inetaddress> addrs = collections.list(intf .getinetaddresses()); (inetaddress addr : addrs) { // log.v(tag, "inside"); if (!addr.isloopbackaddress()) { // log.v(tag, "isnt loopback"); string saddr = addr.gethostaddress().touppercase(); log.v(tag, "ip=" + saddr); boolean isipv4 = inetaddressutils.isipv4address(saddr); if (isipv4) { if (saddr.contains("192.168.49.")) { log.v(tag, "ip = " + saddr); return saddr; } } } } } } catch (exception ex) { log.v(tag, "error in parsing"); } // eat exceptions log.v(tag, "returning empty ip address"); return ""; } public static string getmacaddress(string interfacename) { try { list<networkinterface> interfaces = collections .list(networkinterface.getnetworkinterfaces()); (networkinterface intf : interfaces) { if (interfacename != null) { if (!intf.getname().equalsignorecase(interfacename)) continue; } byte[] mac = intf.gethardwareaddress(); if (mac == null) return ""; stringbuilder buf = new stringbuilder(); (int idx = 0; idx < mac.length; idx++) buf.append(string.format("%02x:", mac[idx])); if (buf.length() > 0) buf.deletecharat(buf.length() - 1); return buf.tostring(); } } catch (exception ex) { } // eat exceptions return ""; /* * try { // linux hack return * loadfileasstring("/sys/class/net/" +interfacename + * "/address").touppercase().trim(); } catch (ioexception ex) { return * null; } */ }
Comments
Post a Comment