diff --git a/.idea/misc.xml b/.idea/misc.xml index 3963879..75dac50 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -24,7 +24,7 @@ - + diff --git a/app/build.gradle b/app/build.gradle index a98b663..f850fa5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -21,11 +21,14 @@ android { dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) + compile 'com.android.support:support-v4:25.4.0' androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.android.support:design:25.3.1' + compile 'com.pddstudio:encrypted-preferences:1.3.0' + compile 'com.github.iotaledger:iota~lib~java:0.9.10' testCompile 'junit:junit:4.12' } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c91058d..71572d0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -12,6 +12,7 @@ + - + + + - - - - - - - + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/flashwifi/wifip2p/AccessPointService.java b/app/src/main/java/com/flashwifi/wifip2p/AccessPointService.java index 183b9da..d19cdd6 100644 --- a/app/src/main/java/com/flashwifi/wifip2p/AccessPointService.java +++ b/app/src/main/java/com/flashwifi/wifip2p/AccessPointService.java @@ -8,38 +8,42 @@ import android.os.Binder; import android.os.IBinder; import android.util.Log; -import java.util.Random; - public class AccessPointService extends Service { public final static String TAG = "AccessPointService"; // Binder given to clients private final IBinder mBinder = new LocalBinder(); - // Random number generator - private final Random mGenerator = new Random(); private boolean setup = false; // broadcast stuff - WifiP2pManager mManager; - WifiP2pManager.Channel mChannel; BroadcastReceiver mReceiver; - IntentFilter mIntentFilter; // socket stuff AccessPointTask apTask; - boolean apRuns; + boolean apRuns = false; public void startAP() { - Log.d("", "start AP"); + Log.d("xxxxxxxxxxxxxx", "start AP"); if (!apRuns) { apRuns = true; + apTask = new AccessPointTask(); apTask.execute(this); } else { Log.d("", "startSocketServer: ALREADY RUNNING"); } } + public void stopAP() { + Log.d("xxxxxxxxxxxxxx", "stop AP"); + if (apRuns) { + apRuns = false; + apTask.cancel(true); + } else { + Log.d("", "startSocketServer: ALREADY RUNNING"); + } + } + /** * Class used for the client Binder. Because we know this service always @@ -66,7 +70,6 @@ public class AccessPointService extends Service { @Override public void onCreate() { super.onCreate(); - apTask = new AccessPointTask(); } private void sendUpdateUIBroadcast(){ diff --git a/app/src/main/java/com/flashwifi/wifip2p/AccessPointTask.java b/app/src/main/java/com/flashwifi/wifip2p/AccessPointTask.java index 9850382..430eb39 100644 --- a/app/src/main/java/com/flashwifi/wifip2p/AccessPointTask.java +++ b/app/src/main/java/com/flashwifi/wifip2p/AccessPointTask.java @@ -10,16 +10,21 @@ import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import static android.content.Context.WIFI_SERVICE; + public class AccessPointTask extends AsyncTask { private final static String TAG = "AccessPointTask"; + private Context context; + String ssid = "iota-wifi-121431"; + WifiManager wifi; + WifiInfo w; @Override protected String doInBackground(Context... params) { - String ssid = "iota-wifi-121431"; - Context context = params[0]; - WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); - WifiInfo w = wifi.getConnectionInfo(); + context = params[0]; + wifi = (WifiManager) context.getSystemService(WIFI_SERVICE); + w = wifi.getConnectionInfo(); Log.d("dsd", w.toString()); if (wifi.isWifiEnabled()) @@ -33,16 +38,12 @@ public class AccessPointTask extends AsyncTask { if (method.getName().equals("setWifiApEnabled")){ methodFound = true; WifiConfiguration netConfig = new WifiConfiguration(); - netConfig.SSID = "\""+ssid+"\""; - netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); - //netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); - //netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); - //netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); - //netConfig.preSharedKey = password; - //netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); - //netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); - //netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); - //netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); + netConfig.SSID = "Iotify"; + netConfig.preSharedKey = "1234567890"; + netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); + netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); try { boolean apstatus = (Boolean) method.invoke(wifi, netConfig,true); @@ -65,7 +66,7 @@ public class AccessPointTask extends AsyncTask { if(apstatus) { - System.out.println("SUCCESSdddd"); + System.out.println("SUCCESS"); //statusView.append("\nAccess Point Created!"); //finish(); //Intent searchSensorsIntent = new Intent(this,SearchSensors.class); @@ -92,11 +93,52 @@ public class AccessPointTask extends AsyncTask { if (!methodFound){ //statusView.setText("Your phone's API does not contain setWifiApEnabled method to configure an access point"); } + + int number_minutes = 60; + for (int i=0; i(); @@ -144,6 +151,28 @@ public class ChatActivity extends AppCompatActivity { listView.setAdapter(listAdapter); } + public void toggleHotspot() { + if (hotspot_running) { + stopHotspot(); + } else { + startHotspot(); + } + } + + private void startHotspot() { + apService.startAP(); + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setImageResource(R.drawable.icon_tethering_on); + hotspot_running = true; + } + + private void stopHotspot() { + apService.stopAP(); + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setImageResource(R.drawable.icon_tethering_off); + hotspot_running = false; + } + public void addMessageLeft(String name, String text) { listAdapter.notifyDataSetInvalidated(); listAdapter.add(name + ": " + text); @@ -169,7 +198,7 @@ public class ChatActivity extends AppCompatActivity { mService = binder.getService(); mBound = true; // start connection - connectToPeer(address); + // connectToPeer(address); } @Override @@ -189,9 +218,7 @@ public class ChatActivity extends AppCompatActivity { apService = binder.getService(); //apBound = true; // start connection - //connectToPeer(address); - apService.startAP(); - + connectToPeer(address); } @Override diff --git a/app/src/main/java/com/flashwifi/wifip2p/DesktopActivity.java b/app/src/main/java/com/flashwifi/wifip2p/DesktopActivity.java new file mode 100644 index 0000000..2ea33ff --- /dev/null +++ b/app/src/main/java/com/flashwifi/wifip2p/DesktopActivity.java @@ -0,0 +1,22 @@ +package com.flashwifi.wifip2p; + +import android.content.Intent; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; + +public class DesktopActivity extends AppCompatActivity { + + private String password; + private String seed; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_desktop); + + // get the secrets from the login screen + Intent intent = getIntent(); + password = intent.getStringExtra("password"); + seed = intent.getStringExtra("seed"); + } +} diff --git a/app/src/main/java/com/flashwifi/wifip2p/HomeActivity.java b/app/src/main/java/com/flashwifi/wifip2p/HomeActivity.java new file mode 100644 index 0000000..46ed1f4 --- /dev/null +++ b/app/src/main/java/com/flashwifi/wifip2p/HomeActivity.java @@ -0,0 +1,184 @@ +package com.flashwifi.wifip2p; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.support.design.widget.Snackbar; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ProgressBar; +import android.widget.TextView; + +import com.pddstudio.preferences.encrypted.EncryptedPreferences; + +import jota.utils.SeedRandomGenerator; + +public class HomeActivity extends AppCompatActivity { + + private static final String TAG = "Home"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_home); + } + + private void setProgressBar(int percentage) { + ProgressBar prog = (ProgressBar) findViewById(R.id.progressbar); + prog.setProgress(percentage); + } + + private void showPasswordField() { + // show the password field + final EditText field = (EditText) findViewById(R.id.password); + field.setVisibility(View.VISIBLE); + + // show the submit button + Button button = (Button) findViewById(R.id.decryptTheSeedButton); + button.setVisibility(View.VISIBLE); + button.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(final View view) { + String password = field.getText().toString(); + decryptSeed(password); + } + }); + } + + private void startDesktop(String seed, String password) { + // the security of this: + // https://stackoverflow.com/questions/24141480/securi ty-of-sending-sensitive-intent-extras-within-my-own-app + Intent intent = new Intent(this, MainActivity.class); + intent.putExtra("seed", seed); + intent.putExtra("password", password); + startActivity(intent); + + } + + private void decryptSeed(String password) { + EncryptedPreferences encryptedPreferences = new EncryptedPreferences.Builder(this).withEncryptionPassword(password).build(); + String seed = encryptedPreferences.getString(getString(R.string.encrypted_seed), null); + View view = findViewById(R.id.home_view); + + if (seed != null) { + Snackbar.make(view, getString(R.string.seed_decrypted), Snackbar.LENGTH_LONG).setAction("Action", null).show(); + setProgressBar(90); + startDesktop(seed, password); + } else { + final EditText field = (EditText) findViewById(R.id.password); + field.setText(""); + Snackbar.make(view, getString(R.string.wrong_password), Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + } + + private void showGenerateSeedButton() { + Button button = (Button) findViewById(R.id.generateSeedButton); + button.setVisibility(View.VISIBLE); + button.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(final View view) { + generateNewSeed(); + } + }); + } + + private void generateNewSeed() { + // generate the seed + final String seed = SeedRandomGenerator.generateNewSeed(); + + TextView seedText = (TextView) findViewById(R.id.seedTextView); + seedText.setVisibility(View.VISIBLE); + seedText.setText(seed); + setProgressBar(25); + + // show password comment string + TextView seedComment = (TextView) findViewById(R.id.seedComment); + seedComment.setVisibility(View.VISIBLE); + + // show new password field + final EditText new_password_field = (EditText) findViewById(R.id.new_password); + new_password_field.setVisibility(View.VISIBLE); + + // show the button + Button button = (Button) findViewById(R.id.new_password_button); + button.setVisibility(View.VISIBLE); + setProgressBar(35); + + button.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(final View view) { + setProgressBar(50); + String password = new_password_field.getText().toString(); + storeNewSeed(seed, password); + } + }); + } + + private void storeNewSeed(String seed, String password) { + // store the seed encrypted + EncryptedPreferences encryptedPreferences = new EncryptedPreferences.Builder(this).withEncryptionPassword(password).build(); + encryptedPreferences.edit() + .putString(getString(R.string.encrypted_seed), seed) + .apply(); + setProgressBar(60); + // store the status in plain mode + SharedPreferences sharedPref = this.getSharedPreferences( + getString(R.string.preference_file_key), Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedPref.edit(); + editor.putBoolean(getString(R.string.active_seed), true); + editor.apply(); + // display a message to the user + View view = findViewById(R.id.home_view); + Snackbar.make(view, getString(R.string.seed_stored), Snackbar.LENGTH_LONG).setAction("Action", null).show(); + setProgressBar(90); + + // start the next activity + startDesktop(seed, password); + } + + private void checkStorage() { + setProgressBar(10); + SharedPreferences sharedPref = this.getSharedPreferences( + getString(R.string.preference_file_key), Context.MODE_PRIVATE); + setProgressBar(12); + // how many times has the app been opened? + int numberOfUsages = sharedPref.getInt(getString(R.string.number_of_usages), 0); + setProgressBar(14); + // update the number + SharedPreferences.Editor editor = sharedPref.edit(); + editor.putInt(getString(R.string.number_of_usages), numberOfUsages + 1); + editor.apply(); + + // get the current view + final View view = findViewById(R.id.home_view); + + if (numberOfUsages == 0) { + // change the view to the tutorial and settings page + // setProgressBar(90); + } + + // is there an active seed + boolean activeSeed = sharedPref.getBoolean(getString(R.string.active_seed), false); + setProgressBar(16); + + if (activeSeed) { + // show password field + showPasswordField(); + setProgressBar(20); + } else { + Snackbar.make(view, getString(R.string.no_seed_present), Snackbar.LENGTH_LONG).setAction("Action", null).show(); + setProgressBar(20); + showGenerateSeedButton(); + } + } + + @Override + protected void onStart() { + super.onStart(); + checkStorage(); + } +} diff --git a/app/src/main/java/com/flashwifi/wifip2p/HotspotFragment.java b/app/src/main/java/com/flashwifi/wifip2p/HotspotFragment.java new file mode 100644 index 0000000..7943a19 --- /dev/null +++ b/app/src/main/java/com/flashwifi/wifip2p/HotspotFragment.java @@ -0,0 +1,325 @@ +package com.flashwifi.wifip2p; + +import android.app.Fragment; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.net.wifi.p2p.WifiP2pInfo; +import android.net.wifi.p2p.WifiP2pManager; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.ToggleButton; + +import java.net.InetAddress; +import java.util.ArrayList; + +import jota.IotaAPI; +import jota.dto.response.GetNodeInfoResponse; + + +public class HotspotFragment extends Fragment { + + public final static String TAG = "HotspotFragment"; + + private int numberConnectedPeers = 0; + + WiFiDirectBroadcastService mService; + boolean mBound = false; + BroadcastReceiver updateUIReceiver; + + Messenger xService = null; + /** Flag indicating whether we have called bind on the service. */ + boolean xIsBound; + + static class IncomingHandler extends Handler { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MessengerService.MSG_SET_VALUE: + Log.d(TAG, "Received from service: " + msg.arg1); + break; + default: + super.handleMessage(msg); + } + } + } + + /** + * Target we publish for clients to send messages to IncomingHandler. + */ + final Messenger xMessenger = new Messenger(new SearchActivity.IncomingHandler()); + + /** + * Class for interacting with the main interface of the service. + */ + private ServiceConnection xConnection = new ServiceConnection() { + public void onServiceConnected(ComponentName className, + IBinder service) { + // This is called when the connection with the service has been + // established, giving us the service object we can use to + // interact with the service. We are communicating with our + // service through an IDL interface, so get a client-side + // representation of that from the raw service object. + xService = new Messenger(service); + + // We want to monitor the service for as long as we are + // connected to it. + try { + Message msg = Message.obtain(null, + MessengerService.MSG_REGISTER_CLIENT); + msg.replyTo = xMessenger; + xService.send(msg); + + // Give it some value as an example. + msg = Message.obtain(null, + MessengerService.MSG_SET_VALUE, this.hashCode(), 0); + xService.send(msg); + } catch (RemoteException e) { + // In this case the service has crashed before we could even + // do anything with it; we can count on soon being + // disconnected (and then reconnected if it can be restarted) + // so there is no need to do anything here. + } + } + + public void onServiceDisconnected(ComponentName className) { + // This is called when the connection with the service has been + // unexpectedly disconnected -- that is, its process crashed. + xService = null; + } + }; + + void doBindService() { + // Establish a connection with the service. We use an explicit + // class name because there is no reason to be able to let other + // applications replace our component. + getActivity().bindService(new Intent(getActivity(), MessengerService.class), xConnection, Context.BIND_AUTO_CREATE); + xIsBound = true; + } + + void doUnbindService() { + if (xIsBound) { + // If we have received the service, and hence registered with + // it, then now is the time to unregister. + if (xService != null) { + try { + Message msg = Message.obtain(null, + MessengerService.MSG_UNREGISTER_CLIENT); + msg.replyTo = xMessenger; + xService.send(msg); + } catch (RemoteException e) { + // There is nothing special we need to do if the service + // has crashed. + } + } + + // Detach our existing connection. + getActivity().unbindService(xConnection); + xIsBound = false; + } + } + + public HotspotFragment() { + // Empty constructor required for fragment subclasses + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View rootView = inflater.inflate(R.layout.fragment_hotspot, container, false); + return rootView; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + //setContentView(R.layout.activity_scrolling); + + } + + @Override + public void onStart() { + super.onStart(); + } + + public static HotspotFragment newInstance() + { + HotspotFragment f = new HotspotFragment(); + //Bundle bdl = new Bundle(2); + //bdl.putInt(EXTRA_TITLE, title); + //bdl.putString(EXTRA_MESSAGE, message); + //f.setArguments(bdl); + return f; + } + + private void updateUi(Intent intent) { + Log.d(TAG, "updateUi: Got some network data into the hotspot fragment"); + String numberAvailableDevices = Integer.toString(mService.getArrayList().size()); + TextView text = (TextView) getActivity().findViewById(R.id.numberPeers); + text.setText(String.format("%s peers", numberAvailableDevices)); + final View activity_view = getActivity().findViewById(R.id.drawer_layout); + + if (intent.hasExtra("what") && intent.getExtras().getString("what", "").equals("connectivity_changed")) { + + NetworkInfo network_info = mService.getNetwork_info(); + WifiP2pInfo p2p_info = mService.getP2p_info(); + + if (network_info.getState() == NetworkInfo.State.CONNECTED) { + if (p2p_info.isGroupOwner) { + Snackbar.make(activity_view, "You are the group owner", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + mService.startNegotiationServer(false); + } else { + InetAddress groupOwnerAddress = p2p_info.groupOwnerAddress; + Snackbar.make(activity_view, "You are only a member of the group", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + mService.startNegotiationClient(groupOwnerAddress, false); + } + } + } + } + + @Override + public void onStop() { + super.onStop(); + // getActivity().unbindService(mConnection); + mBound = false; + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + IntentFilter filter = new IntentFilter(); + filter.addAction("jenny.daniel.wifip2p.update_ui"); + + updateUIReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + updateUi(intent); + } + }; + getActivity().registerReceiver(updateUIReceiver, filter); + + // Bind to Service + Intent intent = new Intent(getActivity(), WiFiDirectBroadcastService.class); + getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + + initUI(); + + testInternetConnection(); + testIotaNodeConnection(); + } + + private void testIotaNodeConnection() { + // ToDo: Move this to a async task + /*IotaAPI api = new IotaAPI.Builder() + .protocol("http") + .host("iota.bitfinex.com") + .port("80") + .build(); + GetNodeInfoResponse response = api.getNodeInfo(); + + String latestMilestone = response.getLatestMilestone(); */ + + TextView text = (TextView) getActivity().findViewById(R.id.iotaNodeTest); + text.setVisibility(View.VISIBLE); + + + } + + private void testInternetConnection() { + // ToDo: Move this to a async task + //boolean status = (isNetworkConnected() && isInternetAvailable()); + boolean status = true; + TextView text = (TextView) getActivity().findViewById(R.id.internetTest); + if (status) { + text.setVisibility(View.VISIBLE); + } + } + + private boolean isNetworkConnected() { + ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); + + return cm.getActiveNetworkInfo() != null; + } + + public boolean isInternetAvailable() { + try { + InetAddress ipAddr = InetAddress.getByName("google.com"); + return !ipAddr.getHostAddress().equals(""); + + } catch (Exception e) { + return false; + } + } + + private void startDiscovery() { + final View activity_view = getActivity().findViewById(R.id.drawer_layout); + if (mBound) { + mService.getPeerList(new WifiP2pManager.ActionListener() { + @Override + public void onSuccess() { + Snackbar.make(activity_view, "Successfully searched for peers", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + + @Override + public void onFailure(int reasonCode) { + Snackbar.make(activity_view, "Aaaargh :( Peering problem!", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + }); + } + } + + private void initUI() { + final View activity_view = getActivity().findViewById(R.id.drawer_layout); + final ToggleButton button = (ToggleButton) getActivity().findViewById(R.id.startAPButton); + button.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (button.isChecked()) { + startDiscovery(); + Snackbar.make(activity_view, "Start Discovery Mode", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + } + }); + } + + /** Defines callbacks for service binding, passed to bindService() */ + private ServiceConnection mConnection = new ServiceConnection() { + + @Override + public void onServiceConnected(ComponentName className, + IBinder service) { + // We've bound to LocalService, cast the IBinder and get LocalService instance + WiFiDirectBroadcastService.LocalBinder binder = (WiFiDirectBroadcastService.LocalBinder) service; + mService = binder.getService(); + mBound = true; + } + + @Override + public void onServiceDisconnected(ComponentName arg0) { + mBound = false; + } + }; +} \ No newline at end of file diff --git a/app/src/main/java/com/flashwifi/wifip2p/MainActivity.java b/app/src/main/java/com/flashwifi/wifip2p/MainActivity.java index cd07792..c597f2e 100644 --- a/app/src/main/java/com/flashwifi/wifip2p/MainActivity.java +++ b/app/src/main/java/com/flashwifi/wifip2p/MainActivity.java @@ -1,261 +1,156 @@ package com.flashwifi.wifip2p; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; +import android.app.Fragment; +import android.app.FragmentManager; import android.content.Intent; -import android.content.IntentFilter; -import android.content.ServiceConnection; -import android.net.wifi.p2p.WifiP2pManager; -import android.os.Handler; -import android.os.IBinder; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; +import android.net.Uri; +import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; -import android.support.v7.app.AppCompatActivity; -import android.os.Bundle; -import android.support.v7.widget.Toolbar; -import android.util.Log; +import android.view.LayoutInflater; import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; +import android.support.design.widget.NavigationView; +import android.support.v4.view.GravityCompat; +import android.support.v4.widget.DrawerLayout; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.Menu; +import android.view.MenuItem; +import android.view.ViewGroup; import android.widget.ListView; -import java.util.ArrayList; - -public class MainActivity extends AppCompatActivity { - - public final static String TAG = "MainActivity"; - - WiFiDirectBroadcastService mService; - boolean mBound = false; - BroadcastReceiver updateUIReceiver; - - ArrayList arrayList; - ArrayAdapter listAdapter; - - - - - - - Messenger xService = null; - /** Flag indicating whether we have called bind on the service. */ - boolean xIsBound; - - static class IncomingHandler extends Handler { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case MessengerService.MSG_SET_VALUE: - Log.d(TAG, "Received from service: " + msg.arg1); - break; - default: - super.handleMessage(msg); - } - } - } - - /** - * Target we publish for clients to send messages to IncomingHandler. - */ - final Messenger xMessenger = new Messenger(new IncomingHandler()); - - /** - * Class for interacting with the main interface of the service. - */ - private ServiceConnection xConnection = new ServiceConnection() { - public void onServiceConnected(ComponentName className, - IBinder service) { - // This is called when the connection with the service has been - // established, giving us the service object we can use to - // interact with the service. We are communicating with our - // service through an IDL interface, so get a client-side - // representation of that from the raw service object. - xService = new Messenger(service); - - // We want to monitor the service for as long as we are - // connected to it. - try { - Message msg = Message.obtain(null, - MessengerService.MSG_REGISTER_CLIENT); - msg.replyTo = xMessenger; - xService.send(msg); - - // Give it some value as an example. - msg = Message.obtain(null, - MessengerService.MSG_SET_VALUE, this.hashCode(), 0); - xService.send(msg); - } catch (RemoteException e) { - // In this case the service has crashed before we could even - // do anything with it; we can count on soon being - // disconnected (and then reconnected if it can be restarted) - // so there is no need to do anything here. - } - } - - public void onServiceDisconnected(ComponentName className) { - // This is called when the connection with the service has been - // unexpectedly disconnected -- that is, its process crashed. - xService = null; - } - }; - - void doBindService() { - // Establish a connection with the service. We use an explicit - // class name because there is no reason to be able to let other - // applications replace our component. - bindService(new Intent(this, - MessengerService.class), xConnection, Context.BIND_AUTO_CREATE); - xIsBound = true; - } - - void doUnbindService() { - if (xIsBound) { - // If we have received the service, and hence registered with - // it, then now is the time to unregister. - if (xService != null) { - try { - Message msg = Message.obtain(null, - MessengerService.MSG_UNREGISTER_CLIENT); - msg.replyTo = xMessenger; - xService.send(msg); - } catch (RemoteException e) { - // There is nothing special we need to do if the service - // has crashed. - } - } - - // Detach our existing connection. - unbindService(xConnection); - xIsBound = false; - } - } - - - - - - - +public class MainActivity extends AppCompatActivity + implements NavigationView.OnNavigationItemSelectedListener +{ + private String password; + private String seed; + private DrawerLayout mDrawerLayout; + private ListView mDrawerList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_scrolling); - - initUI(); - } - - @Override - protected void onStart() { - super.onStart(); - - IntentFilter filter = new IntentFilter(); - filter.addAction("jenny.daniel.wifip2p.update_ui"); - - updateUIReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - updateUi(); - } - }; - registerReceiver(updateUIReceiver, filter); - - // Bind to Service - Intent intent = new Intent(this, WiFiDirectBroadcastService.class); - bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - } - - private void updateUi() { - listAdapter.notifyDataSetInvalidated(); - listAdapter.clear(); - listAdapter.addAll(mService.getArrayList()); - listAdapter.notifyDataSetChanged(); - } - - @Override - protected void onStop() { - super.onStop(); - unbindService(mConnection); - mBound = false; - } - - - private void initUI() { + setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); - toolbar.setTitle("Discover Peers"); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(final View view) { - onRefreshButtonClick(); + public void onClick(View view) { + Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) + .setAction("Action", null).show(); } }); - ListView listView = (ListView) findViewById(R.id.peer_list); - arrayList = new ArrayList<>(); + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( + this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); + drawer.addDrawerListener(toggle); + toggle.syncState(); - listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList); - listView.setAdapter(listAdapter); + NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); + navigationView.setNavigationItemSelectedListener(this); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - String[] splittedLine = arrayList.get(i).split(" : "); - String address = splittedLine[1]; - String name = splittedLine[0]; - - startChat(address, name); - } - }); + // get the secrets from the login screen + Intent intent = getIntent(); + password = intent.getStringExtra("password"); + seed = intent.getStringExtra("seed"); } - public void startChat(String address, String name) { - Intent intent = new Intent(this, ChatActivity.class); - intent.putExtra("address", address); - intent.putExtra("name", name); - startActivity(intent); - } - - public void onRefreshButtonClick() { - final View view = findViewById(R.id.main_view); - if (mBound) { - mService.getPeerList(new WifiP2pManager.ActionListener() { - @Override - public void onSuccess() { - Snackbar.make(view, "Successfully searched for peers", Snackbar.LENGTH_LONG).setAction("Action", null).show(); - } - - @Override - public void onFailure(int reasonCode) { - Snackbar.make(view, "Aaaargh :( Peering problem!", Snackbar.LENGTH_LONG).setAction("Action", null).show(); - } - }); + @Override + public void onBackPressed() { + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START); + } else { + super.onBackPressed(); } } - /** Defines callbacks for service binding, passed to bindService() */ - private ServiceConnection mConnection = new ServiceConnection() { + @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; + } - @Override - public void onServiceConnected(ComponentName className, - IBinder service) { - // We've bound to LocalService, cast the IBinder and get LocalService instance - WiFiDirectBroadcastService.LocalBinder binder = (WiFiDirectBroadcastService.LocalBinder) service; - mService = binder.getService(); - mBound = true; + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; } - @Override - public void onServiceDisconnected(ComponentName arg0) { - mBound = false; + return super.onOptionsItemSelected(item); + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public boolean onNavigationItemSelected(MenuItem item) { + // Handle navigation view item clicks here. + int id = item.getItemId(); + + if (id == R.id.nav_search) { + // Handle the camera action + startSearchFragment(); + } else if (id == R.id.nav_start) { + startHotspotFragment(); + } else if (id == R.id.nav_itp) { + + } else if (id == R.id.nav_fund) { + + } else if (id == R.id.nav_withdraw) { + + } else if (id == R.id.nav_conditions) { + + } else if (id == R.id.nav_settings) { + } - }; + + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + drawer.closeDrawer(GravityCompat.START); + return true; + } + + public void startSearchFragment() { + Fragment fragment = new SearchFragment(); + Bundle args = new Bundle(); + //args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); + //fragment.setArguments(args); + + // Insert the fragment by replacing any existing fragment + FragmentManager fragmentManager = getFragmentManager(); + fragmentManager.beginTransaction() + .replace(R.id.content_frame, fragment) + .commit(); + + // Highlight the selected item, update the title, and close the drawer + // mDrawerList.setItemChecked(0, true); + //setTitle(mPlanetTitles[position]); + // mDrawerLayout.closeDrawer(mDrawerList); + } + + public void startHotspotFragment() { + Fragment fragment = new HotspotFragment(); + Bundle args = new Bundle(); + //args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); + //fragment.setArguments(args); + + // Insert the fragment by replacing any existing fragment + FragmentManager fragmentManager = getFragmentManager(); + fragmentManager.beginTransaction() + .replace(R.id.content_frame, fragment) + .commit(); + } + + } diff --git a/app/src/main/java/com/flashwifi/wifip2p/SearchActivity.java b/app/src/main/java/com/flashwifi/wifip2p/SearchActivity.java new file mode 100644 index 0000000..bb79878 --- /dev/null +++ b/app/src/main/java/com/flashwifi/wifip2p/SearchActivity.java @@ -0,0 +1,248 @@ +package com.flashwifi.wifip2p; + +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.net.wifi.p2p.WifiP2pManager; +import android.os.Handler; +import android.os.IBinder; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; + +import java.util.ArrayList; + +public class SearchActivity extends AppCompatActivity { + + public final static String TAG = "SearchActivity"; + + WiFiDirectBroadcastService mService; + boolean mBound = false; + BroadcastReceiver updateUIReceiver; + + ArrayList arrayList; + ArrayAdapter listAdapter; + + Messenger xService = null; + /** Flag indicating whether we have called bind on the service. */ + boolean xIsBound; + + static class IncomingHandler extends Handler { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MessengerService.MSG_SET_VALUE: + Log.d(TAG, "Received from service: " + msg.arg1); + break; + default: + super.handleMessage(msg); + } + } + } + + /** + * Target we publish for clients to send messages to IncomingHandler. + */ + final Messenger xMessenger = new Messenger(new IncomingHandler()); + + /** + * Class for interacting with the main interface of the service. + */ + private ServiceConnection xConnection = new ServiceConnection() { + public void onServiceConnected(ComponentName className, + IBinder service) { + // This is called when the connection with the service has been + // established, giving us the service object we can use to + // interact with the service. We are communicating with our + // service through an IDL interface, so get a client-side + // representation of that from the raw service object. + xService = new Messenger(service); + + // We want to monitor the service for as long as we are + // connected to it. + try { + Message msg = Message.obtain(null, + MessengerService.MSG_REGISTER_CLIENT); + msg.replyTo = xMessenger; + xService.send(msg); + + // Give it some value as an example. + msg = Message.obtain(null, + MessengerService.MSG_SET_VALUE, this.hashCode(), 0); + xService.send(msg); + } catch (RemoteException e) { + // In this case the service has crashed before we could even + // do anything with it; we can count on soon being + // disconnected (and then reconnected if it can be restarted) + // so there is no need to do anything here. + } + } + + public void onServiceDisconnected(ComponentName className) { + // This is called when the connection with the service has been + // unexpectedly disconnected -- that is, its process crashed. + xService = null; + } + }; + + void doBindService() { + // Establish a connection with the service. We use an explicit + // class name because there is no reason to be able to let other + // applications replace our component. + bindService(new Intent(this, + MessengerService.class), xConnection, Context.BIND_AUTO_CREATE); + xIsBound = true; + } + + void doUnbindService() { + if (xIsBound) { + // If we have received the service, and hence registered with + // it, then now is the time to unregister. + if (xService != null) { + try { + Message msg = Message.obtain(null, + MessengerService.MSG_UNREGISTER_CLIENT); + msg.replyTo = xMessenger; + xService.send(msg); + } catch (RemoteException e) { + // There is nothing special we need to do if the service + // has crashed. + } + } + + // Detach our existing connection. + unbindService(xConnection); + xIsBound = false; + } + } + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_scrolling); + + initUI(); + } + + @Override + protected void onStart() { + super.onStart(); + + IntentFilter filter = new IntentFilter(); + filter.addAction("jenny.daniel.wifip2p.update_ui"); + + updateUIReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + updateUi(); + } + }; + registerReceiver(updateUIReceiver, filter); + + // Bind to Service + Intent intent = new Intent(this, WiFiDirectBroadcastService.class); + bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + } + + private void updateUi() { + listAdapter.notifyDataSetInvalidated(); + listAdapter.clear(); + listAdapter.addAll(mService.getArrayList()); + listAdapter.notifyDataSetChanged(); + } + + @Override + protected void onStop() { + super.onStop(); + unbindService(mConnection); + mBound = false; + } + + + private void initUI() { + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + toolbar.setTitle("Discover Peers"); + setSupportActionBar(toolbar); + + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(final View view) { + onRefreshButtonClick(); + } + }); + + ListView listView = (ListView) findViewById(R.id.peer_list); + arrayList = new ArrayList<>(); + + listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList); + listView.setAdapter(listAdapter); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + String[] splittedLine = arrayList.get(i).split(" : "); + String address = splittedLine[1]; + String name = splittedLine[0]; + + startChat(address, name); + } + }); + } + + public void startChat(String address, String name) { + Intent intent = new Intent(this, ChatActivity.class); + intent.putExtra("address", address); + intent.putExtra("name", name); + startActivity(intent); + } + + public void onRefreshButtonClick() { + final View view = findViewById(R.id.main_view); + if (mBound) { + mService.getPeerList(new WifiP2pManager.ActionListener() { + @Override + public void onSuccess() { + Snackbar.make(view, "Successfully searched for peers", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + + @Override + public void onFailure(int reasonCode) { + Snackbar.make(view, "Aaaargh :( Peering problem!", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + }); + } + } + + /** Defines callbacks for service binding, passed to bindService() */ + private ServiceConnection mConnection = new ServiceConnection() { + + @Override + public void onServiceConnected(ComponentName className, + IBinder service) { + // We've bound to LocalService, cast the IBinder and get LocalService instance + WiFiDirectBroadcastService.LocalBinder binder = (WiFiDirectBroadcastService.LocalBinder) service; + mService = binder.getService(); + mBound = true; + } + + @Override + public void onServiceDisconnected(ComponentName arg0) { + mBound = false; + } + }; +} diff --git a/app/src/main/java/com/flashwifi/wifip2p/SearchFragment.java b/app/src/main/java/com/flashwifi/wifip2p/SearchFragment.java new file mode 100644 index 0000000..66c036d --- /dev/null +++ b/app/src/main/java/com/flashwifi/wifip2p/SearchFragment.java @@ -0,0 +1,319 @@ +package com.flashwifi.wifip2p; + +import android.app.Fragment; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.net.NetworkInfo; +import android.net.wifi.p2p.WifiP2pInfo; +import android.net.wifi.p2p.WifiP2pManager; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; + +import java.net.InetAddress; +import java.util.ArrayList; + +/** + * Fragment that appears in the "content_frame", shows a planet + */ +public class SearchFragment extends Fragment { + + public final static String TAG = "SearchActivity"; + + WiFiDirectBroadcastService mService; + boolean mBound = false; + BroadcastReceiver updateUIReceiver; + + ArrayList arrayList; + ArrayAdapter listAdapter; + + Messenger xService = null; + /** Flag indicating whether we have called bind on the service. */ + boolean xIsBound; + + static class IncomingHandler extends Handler { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MessengerService.MSG_SET_VALUE: + Log.d(TAG, "Received from service: " + msg.arg1); + break; + default: + super.handleMessage(msg); + } + } + } + + /** + * Target we publish for clients to send messages to IncomingHandler. + */ + final Messenger xMessenger = new Messenger(new SearchActivity.IncomingHandler()); + + /** + * Class for interacting with the main interface of the service. + */ + private ServiceConnection xConnection = new ServiceConnection() { + public void onServiceConnected(ComponentName className, + IBinder service) { + // This is called when the connection with the service has been + // established, giving us the service object we can use to + // interact with the service. We are communicating with our + // service through an IDL interface, so get a client-side + // representation of that from the raw service object. + xService = new Messenger(service); + + // We want to monitor the service for as long as we are + // connected to it. + try { + Message msg = Message.obtain(null, + MessengerService.MSG_REGISTER_CLIENT); + msg.replyTo = xMessenger; + xService.send(msg); + + // Give it some value as an example. + msg = Message.obtain(null, + MessengerService.MSG_SET_VALUE, this.hashCode(), 0); + xService.send(msg); + } catch (RemoteException e) { + // In this case the service has crashed before we could even + // do anything with it; we can count on soon being + // disconnected (and then reconnected if it can be restarted) + // so there is no need to do anything here. + } + } + + public void onServiceDisconnected(ComponentName className) { + // This is called when the connection with the service has been + // unexpectedly disconnected -- that is, its process crashed. + xService = null; + } + }; + + void doBindService() { + // Establish a connection with the service. We use an explicit + // class name because there is no reason to be able to let other + // applications replace our component. + getActivity().bindService(new Intent(getActivity(), MessengerService.class), xConnection, Context.BIND_AUTO_CREATE); + xIsBound = true; + } + + void doUnbindService() { + if (xIsBound) { + // If we have received the service, and hence registered with + // it, then now is the time to unregister. + if (xService != null) { + try { + Message msg = Message.obtain(null, + MessengerService.MSG_UNREGISTER_CLIENT); + msg.replyTo = xMessenger; + xService.send(msg); + } catch (RemoteException e) { + // There is nothing special we need to do if the service + // has crashed. + } + } + + // Detach our existing connection. + getActivity().unbindService(xConnection); + xIsBound = false; + } + } + + public SearchFragment() { + // Empty constructor required for fragment subclasses + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View rootView = inflater.inflate(R.layout.fragment_search, container, false); + //int i = getArguments().getInt(ARG_PLANET_NUMBER); + //String planet = getResources().getStringArray(R.array.planets_array)[i]; + + //int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), + // "drawable", getActivity().getPackageName()); + //((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId); + //getActivity().setTitle(planet); + + // initUI(); + + return rootView; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + //setContentView(R.layout.activity_scrolling); + + } + + @Override + public void onStart() { + super.onStart(); + } + + public static SearchFragment newInstance() + { + SearchFragment f = new SearchFragment(); + //Bundle bdl = new Bundle(2); + //bdl.putInt(EXTRA_TITLE, title); + //bdl.putString(EXTRA_MESSAGE, message); + //f.setArguments(bdl); + return f; + } + + private void updateUi(Intent intent) { + listAdapter.notifyDataSetInvalidated(); + listAdapter.clear(); + listAdapter.addAll(mService.getArrayList()); + listAdapter.notifyDataSetChanged(); + + String what = intent.getStringExtra("what"); + Log.d(">>>>>>>>>>>>", "updateUi: " + what); + + if (what == null) { + what = ""; + } + + if (what.equals("connectivity_changed")) { + + NetworkInfo network_info = mService.getNetwork_info(); + WifiP2pInfo p2p_info = mService.getP2p_info(); + + if (network_info.getState() == NetworkInfo.State.CONNECTED) { + if (p2p_info.isGroupOwner) { + Log.d(TAG, "You are the group owner"); + mService.startNegotiationServer(true); + Log.d(TAG, "SocketServer started"); + } else { + Log.d(TAG, "You are a member of the group"); + // groupOwnerAddress = p2p_info.groupOwnerAddress; + InetAddress groupOwnerAddress = p2p_info.groupOwnerAddress; + Log.d(TAG, "Group owner address: " + p2p_info.groupOwnerAddress.getHostAddress()); + mService.startNegotiationClient(groupOwnerAddress, true); + Log.d(TAG, "Client Socket started"); + } + } + } + } + + @Override + public void onStop() { + super.onStop(); + getActivity().unbindService(mConnection); + mBound = false; + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + IntentFilter filter = new IntentFilter(); + filter.addAction("jenny.daniel.wifip2p.update_ui"); + + updateUIReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + Log.d("", "onReceive: FRAGMENT HAT WAS"); + updateUi(intent); + } + }; + getActivity().registerReceiver(updateUIReceiver, filter); + + // Bind to Service + Intent intent = new Intent(getActivity(), WiFiDirectBroadcastService.class); + getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + + initUI(); + } + + private void initUI() { + Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar); + toolbar.setTitle("Discover Peers"); + //setSupportActionBar(toolbar); + + FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(final View view) { + onRefreshButtonClick(); + } + }); + + ListView listView = (ListView) getActivity().findViewById(R.id.peer_list); + arrayList = new ArrayList<>(); + + listAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, arrayList); + listView.setAdapter(listAdapter); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + String[] splittedLine = arrayList.get(i).split(" : "); + String address = splittedLine[1]; + String name = splittedLine[0]; + + startChat(address, name); + } + }); + } + + public void startChat(String address, String name) { + Intent intent = new Intent(getActivity(), ChatActivity.class); + intent.putExtra("address", address); + intent.putExtra("name", name); + startActivity(intent); + } + + public void onRefreshButtonClick() { + final View view = getActivity().findViewById(R.id.main_view); + if (mBound) { + mService.getPeerList(new WifiP2pManager.ActionListener() { + @Override + public void onSuccess() { + Snackbar.make(view, "Successfully searched for peers", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + + @Override + public void onFailure(int reasonCode) { + Snackbar.make(view, "Aaaargh :( Peering problem!", Snackbar.LENGTH_LONG).setAction("Action", null).show(); + } + }); + } + } + + /** Defines callbacks for service binding, passed to bindService() */ + private ServiceConnection mConnection = new ServiceConnection() { + + @Override + public void onServiceConnected(ComponentName className, + IBinder service) { + // We've bound to LocalService, cast the IBinder and get LocalService instance + WiFiDirectBroadcastService.LocalBinder binder = (WiFiDirectBroadcastService.LocalBinder) service; + mService = binder.getService(); + mBound = true; + } + + @Override + public void onServiceDisconnected(ComponentName arg0) { + mBound = false; + } + }; +} \ No newline at end of file diff --git a/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastReceiver.java b/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastReceiver.java index c02b831..0fad206 100644 --- a/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastReceiver.java +++ b/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastReceiver.java @@ -22,7 +22,7 @@ public class WiFiDirectBroadcastReceiver extends BroadcastReceiver { private WifiP2pManager mManager; private WifiP2pManager.Channel mChannel; - private MainActivity mActivity; + private SearchActivity mActivity; private WiFiDirectBroadcastService service; @@ -86,9 +86,19 @@ public class WiFiDirectBroadcastReceiver extends BroadcastReceiver { Log.d(TAG, "onReceive: " + network_info.getState().toString()); service.setConnectionStateChanged(p2p_info, network_info, p2p_group); + + mManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() { + @Override + public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) { + service.setNewIncomingConnection(wifiP2pInfo); + } + }); + } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { Log.d(TAG, "onReceive: WIFI_P2P_THIS_DEVICE_CHANGED_ACTION"); // Respond to this device's wifi state changing } } + + } \ No newline at end of file diff --git a/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastService.java b/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastService.java index 4b9e107..4b1606c 100644 --- a/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastService.java +++ b/app/src/main/java/com/flashwifi/wifip2p/WiFiDirectBroadcastService.java @@ -12,6 +12,7 @@ import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.os.Binder; import android.os.IBinder; +import android.support.design.widget.Snackbar; import android.util.Log; import java.net.InetAddress; @@ -42,16 +43,27 @@ public class WiFiDirectBroadcastService extends Service { ArrayList receivedMessages = new ArrayList<>(); // socket stuff - ServerTask serverTask; + NegotiationServerTask negotiationServerTask; boolean serverRuns; - public void startSocketServer() { + private String currentDeviceConnected = null; + + // discovery mode + private boolean discoveryModeActive = false; + + public void startNegotiationServer(boolean isClient) { Log.d("", "startSocketServer: "); - if (!serverRuns) { - serverTask.execute(); - } else { - Log.d("", "startSocketServer: ALREADY RUNNING"); - } + //negotiationServerTask = new NegotiationServerTask(); + //negotiationServerTask.execute(); + String isClientString = (isClient) ? "True" : "False"; + new NegotiationServerTask().execute(isClientString); + } + + public void startNegotiationClient(InetAddress address, boolean isClient) { + Log.d("", "startSocketClient: "); + String isClientString = (isClient) ? "True" : "False"; + String ipaddr = address.getHostAddress(); + new NegotiationClientTask().execute(isClientString, ipaddr); } public void sendMessageToSocketServer(InetAddress address, String message) { @@ -84,7 +96,6 @@ public class WiFiDirectBroadcastService extends Service { registerReceiver(mReceiver, mIntentFilter); - serverTask = new ServerTask(); serverRuns = false; @@ -92,6 +103,11 @@ public class WiFiDirectBroadcastService extends Service { } } + public void startDiscoveryMode(WifiP2pManager.ActionListener action_listener) { + mManager.discoverPeers(mChannel, action_listener); + discoveryModeActive = true; + } + /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. @@ -142,11 +158,21 @@ public class WiFiDirectBroadcastService extends Service { sendUpdateUIBroadcast(); } + public void setNewIncomingConnection(WifiP2pInfo wifiP2pInfo){ + // This method is called when a new device connected to this one + this.p2p_info = wifiP2pInfo; + if (p2p_info.groupFormed) { + if (currentDeviceConnected == null || !currentDeviceConnected.equals(p2p_info.groupOwnerAddress.getHostAddress())) { + currentDeviceConnected = p2p_info.groupOwnerAddress.getHostAddress(); + sendUpdateUIBroadcastNewConnection(); + } + } + } + public void setConnectionStateChanged(WifiP2pInfo p2p_info, NetworkInfo network_info, WifiP2pGroup p2p_group) { this.p2p_info = p2p_info; this.network_info = network_info; this.p2p_group = p2p_group; - sendUpdateUIBroadcast(); } private void sendUpdateUIBroadcast(){ @@ -155,6 +181,14 @@ public class WiFiDirectBroadcastService extends Service { this.sendBroadcast(local); } + private void sendUpdateUIBroadcastNewConnection(){ + Log.d(TAG, "sendUpdateUIBroadcastNewConnection: SEND THEEM SHIIIIIIIT"); + Intent local = new Intent(); + local.setAction("jenny.daniel.wifip2p.update_ui"); + local.putExtra("what", "connectivity_changed"); + this.sendBroadcast(local); + } + private void sendUpdateUIBroadcastWithMessage(String message){ Intent local = new Intent(); local.putExtra("message", message); @@ -166,6 +200,10 @@ public class WiFiDirectBroadcastService extends Service { WifiP2pDevice device; WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = address; + // groupOwnerIntent determines how much you want to become the group onwer + // 0 means little and 15 means a lot + // https://stackoverflow.com/questions/18703881/how-to-make-a-specific-group-owner-in-wifi-direct-android + config.groupOwnerIntent = 0; mManager.connect(mChannel, config, actionListener); } } \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_attach_money.png b/app/src/main/res/drawable/ic_attach_money.png new file mode 100644 index 0000000..c94dc6a Binary files /dev/null and b/app/src/main/res/drawable/ic_attach_money.png differ diff --git a/app/src/main/res/drawable/ic_compare_arrows.png b/app/src/main/res/drawable/ic_compare_arrows.png new file mode 100644 index 0000000..922c28a Binary files /dev/null and b/app/src/main/res/drawable/ic_compare_arrows.png differ diff --git a/app/src/main/res/drawable/ic_keyboard_arrow_right.png b/app/src/main/res/drawable/ic_keyboard_arrow_right.png new file mode 100644 index 0000000..073583e Binary files /dev/null and b/app/src/main/res/drawable/ic_keyboard_arrow_right.png differ diff --git a/app/src/main/res/layout/activity_chat.xml b/app/src/main/res/layout/activity_chat.xml index c4f8d47..3d0affb 100644 --- a/app/src/main/res/layout/activity_chat.xml +++ b/app/src/main/res/layout/activity_chat.xml @@ -5,7 +5,8 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" - tools:context="com.flashwifi.wifip2p.MainActivity"> + android:id="@+id/chatView" + tools:context="com.flashwifi.wifip2p.ChatActivity"> + app:srcCompat="@drawable/icon_tethering_off" /> + + + + + +