Android Open Source - sodf Main Activity






From Project

Back to project page sodf.

License

The source code is released under:

Copyright (c) 2013 Lorenz Lehmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Sof...

If you think the Android project sodf listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package lal.apps.ontap;
/*w w  w .  java2 s  . c  o  m*/
import java.util.LinkedList;
import java.util.List;

import lal.sodf.framework.SodfCallback;
import lal.sodf.framework.SodfFramework;
import lal.sodf.framework.SodfWrapper;
import lal.sodf.framework.ontology.KeyNode;
import lal.sodf.framework.ontology.KeyValueNode;
import lal.sodf.framework.ontology.Node;
import lal.sodf.framework.ontology.SodfTree;
import lal.sodf.framework.ontology.SodfVocabulary;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements SodfCallback {

  private Handler handler;
  private PendingIntent pendingIntent;
  private MainActivity self;
  private boolean writeOnTap = false;
  private SodfWrapper writeData = null;
  private AlertDialog dialog;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    self = this;
    handler = new Handler();
    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
  }
  
  /** 
   * Function that is triggered when the user clicks on the write data button 
   */
  public void writeClicked(View v){
    //gather the Wifi information
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wi = wm.getConnectionInfo();
    if (wi == null || wi.getNetworkId() == -1){
      Toast toast = Toast.makeText(this, "You are not connected to a Wifi network.", Toast.LENGTH_LONG);
      toast.show();
      return;
    }
    //check which of the configured configurations is active
    WifiConfiguration active = null;
    for (WifiConfiguration con : wm.getConfiguredNetworks()){
      if (con.networkId == wi.getNetworkId()){
        active = con;
        break;
      }
    }
    //check if the current connection is saved in the settings
    if (active == null){
      Toast toast = Toast.makeText(this, "Your current network is not stored in the settings.", Toast.LENGTH_LONG);
      toast.show();
      return;
    }

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    final String SSID = active.SSID;
    new AlertDialog.Builder(this)
    .setTitle("Enter Password")
    .setMessage("Please enter the password for the Wifi network: "+active.SSID)
    .setView(input)
    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        String password = input.getText()+""; 
        //hide the soft keyboard
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
        //store the collected data on a NFC tag
        writeDataTree(SSID, password);
      }
    })
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        // Do nothing.
      }
    }).show();
  }
  
  /**
   * Write the connection info for a wifi element on a tag
   * @param SSID SSID if the network
   * @param pw Required password to connect to the network
   */
  private void writeDataTree(String SSID, String pw){
    //build a SODF function with the information
    SodfTree tree = new SodfTree();
    List<Node> interactions = new LinkedList<Node>();
    interactions.add(new KeyValueNode(WifiVocabulary.WIFI_SSID,SSID));
    interactions.add(new KeyValueNode(WifiVocabulary.WIFI_PASSWORD, pw));//this only gets the password for WPA
    tree.getFunctionsSubtree().addNewFunction(WifiVocabulary.WIFI_FUNCTION, interactions);

    //store the tree in a wrapper object and signal that the app is ready to write data
    writeData = new SodfWrapper(tree, "lal.apps.ontap");
    writeOnTap = true;

    //show a message saying the user should tap a NFC tag to write
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Please tap a NFC tag to write the data on it")
    .setTitle("Write Wifi Information")
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
        //turn the write mode off
        writeOnTap = false;
        writeData = null;
      }
    });
    dialog = builder.create();
    dialog.show();     
  }

  @Override
  public void readComplete(final SodfWrapper data) {
    handler.post(new Runnable(){
      @Override
      public void run() {
        try {
          //check if required wifi information is present in the tree
          KeyNode interactions = data.data.getFunctionsSubtree()
              .getKeyNodeChild(WifiVocabulary.WIFI_FUNCTION)
              .getKeyNodeChild(SodfVocabulary.SODF_INTERACTION);
          //see this for examples on how to connect: http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
          WifiConfiguration config = new WifiConfiguration();
          config.SSID = interactions.getKeyValueNodeChild(WifiVocabulary.WIFI_SSID).getFirstValue();
          config.preSharedKey = "\""+ interactions.getKeyValueNodeChild(WifiVocabulary.WIFI_PASSWORD).getFirstValue() +"\"";//only supports WPA networks

          //check if the wifi network is already saved
          WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
          WifiConfiguration connection = null;
          for (WifiConfiguration con : wm.getConfiguredNetworks()){
            if (con.SSID.equals(config.SSID)){
              connection = con;
              break;
            }
          }
          
          if (connection != null){//if the network is already in the list just switch it on
            wm.enableNetwork(connection.networkId, true);            
          }
          else {//add the wifi network
            int id = wm.addNetwork(config);
            //directly connect to the network
            wm.enableNetwork(id, true);
            //remember the network in the future
            wm.saveConfiguration();
          }

          Toast toast = Toast.makeText(self, "Successfullt connected to Wifi network: "+config.SSID, Toast.LENGTH_LONG);
          toast.show();
        }
        catch (final NullPointerException e){//this happens if the user scans a tag that does not contain the required information
          Log.e("OnTap", "Error on readComplete: "+e);
          Toast toast = Toast.makeText(self, "Error. Looks like the tag you scanned did not contain the required information.", Toast.LENGTH_LONG);
          toast.show();                    


        }
      }
    });
  }

  @Override
  public void writeComplete(final int resultCode) {
    handler.post(new Runnable() {
      @Override
      public void run() {
        writeData = null;
        writeOnTap = false;
        //close the dialog if it was open
        if (dialog != null) dialog.cancel();
        //show a toast based on the read result
        Toast toast;
        switch (resultCode){
        case SodfCallback.WRITE_IO_EXCEPTION: toast = Toast.makeText(self, "IO exception when writing. Please try againg!", Toast.LENGTH_LONG); break;
        case SodfCallback.WRITE_FORMAT_EXCEPTION: toast = Toast.makeText(self, "Format exception when writing. Please try againg!", Toast.LENGTH_LONG); break;
        default: toast = Toast.makeText(self, "Write successful", Toast.LENGTH_LONG);
        }
        toast.show();
      }
    });    
  }
  
  /* (non-Javadoc)
   * @see android.app.Activity#onPause()
   */
  @Override
  protected void onPause() {
    //has to be disabled because the app is not in foreground anymore
    NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this);
    super.onPause();
  }
  
  /* (non-Javadoc)
   * @see android.app.Activity#onResume()
   */
  @Override
  protected void onResume() {
    super.onResume();
    //register to get all NFC tags
    NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this, pendingIntent, null, null);
  }
  
  /* (non-Javadoc)
   * @see android.app.Activity#onNewIntent(android.content.Intent)
   */
  @Override
  protected void onNewIntent(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    //ensure that a tag was tapped and the user wants to write data
    if (tag != null && writeOnTap == true && writeData != null){
      SodfFramework.writeDataUncompressed(tag, writeData, this);
    }
    else if (tag != null && writeOnTap == false){
      //read the data from the tag
      SodfFramework.readData(tag, this);
    }
  }
}




Java Source Code List

lal.apps.ontap.MainActivity.java
lal.apps.ontap.WifiVocabulary.java
lal.apps.smartfoodenvironment.activities.ExpiredActivity.java
lal.apps.smartfoodenvironment.activities.FactoryActivity.java
lal.apps.smartfoodenvironment.activities.MicrowaveActivity.java
lal.apps.smartfoodenvironment.activities.StartActivity.java
lal.apps.smartfoodenvironment.model.MicrowaveVocabulary.java
lal.apps.smartfoodenvironment.model.ProductFactory.java
lal.apps.smartfoodenvironment.model.ProductVocabulary.java
lal.sodf.example.MainActivity.java
lal.sodf.framework.SodfCallback.java
lal.sodf.framework.SodfCallback.java
lal.sodf.framework.SodfCallback.java
lal.sodf.framework.SodfFramework.java
lal.sodf.framework.SodfFramework.java
lal.sodf.framework.SodfFramework.java
lal.sodf.framework.SodfWrapper.java
lal.sodf.framework.SodfWrapper.java
lal.sodf.framework.SodfWrapper.java
lal.sodf.framework.compressor.CompressionAlgorithm.java
lal.sodf.framework.compressor.CompressionAlgorithm.java
lal.sodf.framework.compressor.CompressionAlgorithm.java
lal.sodf.framework.compressor.Compressor.java
lal.sodf.framework.compressor.Compressor.java
lal.sodf.framework.compressor.Compressor.java
lal.sodf.framework.compressor.Gzip.java
lal.sodf.framework.compressor.Gzip.java
lal.sodf.framework.compressor.Gzip.java
lal.sodf.framework.exceptions.CompressionAlgorithmNotFoundException.java
lal.sodf.framework.exceptions.CompressionAlgorithmNotFoundException.java
lal.sodf.framework.exceptions.CompressionAlgorithmNotFoundException.java
lal.sodf.framework.exceptions.DuplicateKeyException.java
lal.sodf.framework.exceptions.DuplicateKeyException.java
lal.sodf.framework.exceptions.DuplicateKeyException.java
lal.sodf.framework.exceptions.MalformedTypeException.java
lal.sodf.framework.exceptions.MalformedTypeException.java
lal.sodf.framework.exceptions.MalformedTypeException.java
lal.sodf.framework.exceptions.TagEmptyException.java
lal.sodf.framework.exceptions.TagEmptyException.java
lal.sodf.framework.exceptions.TagEmptyException.java
lal.sodf.framework.exceptions.UnformattedTagException.java
lal.sodf.framework.exceptions.UnformattedTagException.java
lal.sodf.framework.exceptions.UnformattedTagException.java
lal.sodf.framework.nfc.NfcContentWrapper.java
lal.sodf.framework.nfc.NfcContentWrapper.java
lal.sodf.framework.nfc.NfcContentWrapper.java
lal.sodf.framework.nfc.NfcHandler.java
lal.sodf.framework.nfc.NfcHandler.java
lal.sodf.framework.nfc.NfcHandler.java
lal.sodf.framework.ontology.FunctionsNode.java
lal.sodf.framework.ontology.FunctionsNode.java
lal.sodf.framework.ontology.FunctionsNode.java
lal.sodf.framework.ontology.KeyNode.java
lal.sodf.framework.ontology.KeyNode.java
lal.sodf.framework.ontology.KeyNode.java
lal.sodf.framework.ontology.KeyValueNode.java
lal.sodf.framework.ontology.KeyValueNode.java
lal.sodf.framework.ontology.KeyValueNode.java
lal.sodf.framework.ontology.MetadataNode.java
lal.sodf.framework.ontology.MetadataNode.java
lal.sodf.framework.ontology.MetadataNode.java
lal.sodf.framework.ontology.Node.java
lal.sodf.framework.ontology.Node.java
lal.sodf.framework.ontology.Node.java
lal.sodf.framework.ontology.PropertiesNode.java
lal.sodf.framework.ontology.PropertiesNode.java
lal.sodf.framework.ontology.PropertiesNode.java
lal.sodf.framework.ontology.RestInteractionNode.java
lal.sodf.framework.ontology.RestInteractionNode.java
lal.sodf.framework.ontology.RestInteractionNode.java
lal.sodf.framework.ontology.RestParameters.java
lal.sodf.framework.ontology.RestParameters.java
lal.sodf.framework.ontology.RestParameters.java
lal.sodf.framework.ontology.SodfTree.java
lal.sodf.framework.ontology.SodfTree.java
lal.sodf.framework.ontology.SodfTree.java
lal.sodf.framework.ontology.SodfVocabulary.java
lal.sodf.framework.ontology.SodfVocabulary.java
lal.sodf.framework.ontology.SodfVocabulary.java
lal.sodf.framework.parser.SodfParser.java
lal.sodf.framework.parser.SodfParser.java
lal.sodf.framework.parser.SodfParser.java