PC_BCR.java :  » Barcode » android-pcbcr » brad » android » pc_bcr » Android Open Source

Android Open Source » Barcode » android pcbcr 
android pcbcr » brad » android » pc_bcr » PC_BCR.java
/*  Copyright 2010 Brad Drehmer

    This file is part of Android PB_BCR.

    Android PB_BCR is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Android PB_BCR is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Android PC_BCR.  If not, see <http://www.gnu.org/licenses/>.
*/

package brad.android.pc_bcr;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class PC_BCR extends Activity {
    
  TextView resultsLogTextView;
  EditText targetIP, targetPort;
  Button scanButton;
  
  String desiredCodeTypes = IntentIntegrator.ALL_CODE_TYPES;
  Boolean continuousScanMode = false;
  
  /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        scanButton = (Button)findViewById(R.id.SCANbutton);
        scanButton.setOnClickListener(mScanListener);
        
        resultsLogTextView = (TextView)findViewById(R.id.resultsLogTextView);
        targetIP = (EditText)findViewById(R.id.IPeditText);
        targetPort = (EditText)findViewById(R.id.PORTeditText);
        
        targetIP.setOnKeyListener(mOnKeyListener);
        targetPort.setOnKeyListener(mOnKeyListener);    
        
        // try to restore state.
      SharedPreferences inState = getPreferences(0);              
        if(inState!=null){
          String ipText = inState.getString("ip", "192.168.1.");
          targetIP.setText(ipText);
          String portText = inState.getString("port", "13000");
          targetPort.setText(portText);
          
          desiredCodeTypes = inState.getString("codeTypes", IntentIntegrator.ALL_CODE_TYPES);
          
          continuousScanMode = inState.getBoolean("continuousScanMode", false); 
        }
    }
    
    @Override
    protected void onPause(){
      super.onPause();
      
      SharedPreferences prefs = getPreferences(0);
     SharedPreferences.Editor outState = prefs.edit();
     
     outState.putString("ip", targetIP.getText().toString());    // save user entries
     outState.putString("port", targetPort.getText().toString());
     outState.putString("codeTypes", desiredCodeTypes);
     outState.putBoolean("continuousScanMode", continuousScanMode);
     
     outState.commit();
    }
    
    // if they hit 'Enter' in one of the input boxes, click the 'Scan' button
    private OnKeyListener mOnKeyListener = new OnKeyListener() {
      public boolean onKey(View v, int keyCode, KeyEvent event) {
        int action = event.getAction(); 
        if( action == KeyEvent.ACTION_UP) {
          int key = event.getUnicodeChar(); 
          if( key == '\n'){
            scanButton.performClick();
            return true;
          }
        }
        return false;
      }
    };
    
    
    private OnClickListener mScanListener = new OnClickListener() {
        public void onClick(View v) {
          //Toast toast = Toast.makeText(getApplicationContext(), "scanning...", Toast.LENGTH_SHORT);
          //toast.show();
          
          // do a quick check of the network parameters that the user has entered before trying to scan
          String targetIPstr;
          try { 
                targetIPstr = targetIP.getText().toString();
                InetAddress serverAddr = InetAddress.getByName(targetIPstr);
                
          } catch (Exception e) { 
                resultsLogTextView.setText("Error in the IP address that you entered...it should have a format similar to \"192.168.1.100\"");
                return;
            }
             
          /* // disabling this ping...some new Android builds don't seem to include ping, or at least don't give user privilege to use it
           try {  // ping host
                Runtime rt = Runtime.getRuntime();
                Process p = rt.exec("ping -c 1 " + targetIPstr);
                BufferedReader BR = new BufferedReader(new InputStreamReader(p.getInputStream()));
                
                String line = "", ping = "";
                
                while ((line = BR.readLine()) != null ) { 
                    
                    ping += line + "\n";                     
                 } 
                 BR.close();
                
                 if (! ping.contains("1 received")){
                   resultsLogTextView.setText("Error pinging the IP address that you entered.");
                      return;
                 }
                  
          } catch (Exception e) { 
                resultsLogTextView.setText("Error pinging the IP address that you entered: " + e.getMessage());
                return;
            }*/
          
          try {                 
                int i_targetPort = Integer.parseInt(targetPort.getText().toString());
          } catch (Exception e) { 
                resultsLogTextView.setText("Error in the port number that you entered...it should be an Integer value.");
              return;
            }
          
          // launch ZXing to scan the barcode 
          // (note that this will prompt them to install ZXing if it isn't installed yet)          
          IntentIntegrator.initiateScan(PC_BCR.this, desiredCodeTypes); // scans specified barcode types          
        }
    };
    
    
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
      
      if (requestCode == SelectCodeTypes.SELECT_CODE_TYPES_REQUESTCODE) {
        if (resultCode == RESULT_OK) {
          String result = intent.getStringExtra("desiredCodes");
          if (result != null) {
            if (result.length() > 0) {
              desiredCodeTypes = result;
              
              Toast toast = Toast.makeText(getApplicationContext(), "saved code preferences: " 
                          + desiredCodeTypes, Toast.LENGTH_SHORT);
                toast.show();
            }
          }
        }
        return;
      }
      
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        
        if (scanResult != null) {
          if (scanResult.getContents() == null)
            return; // null contents when you get a result from them installing ZXing or pressing the 'back' button
          
          //Toast toast = Toast.makeText(getApplicationContext(), 
          //    scanResult.getContents(), Toast.LENGTH_SHORT);
          //toast.show();
          
          //CharSequence existingLog = resultsLogTextView.getText();
          
          resultsLogTextView.setText("");
          
          InetAddress serverAddr;
          int i_targetPort;
          
          try { 
                String targetIPstr = targetIP.getText().toString();
                serverAddr = InetAddress.getByName(targetIPstr); 
          } catch (Exception e) { 
                resultsLogTextView.setText("Error in the IP address that you entered: " + e.getMessage());
              return;
            }
          
          try {                 
                i_targetPort = Integer.parseInt(targetPort.getText().toString());
          } catch (Exception e) { 
                resultsLogTextView.setText("Error in the port number that you entered.  It should be an Integer value.");
              return;
            }

          try {
            // transmit the barcode scan result data back to the PC
              
                //Socket socket = new Socket(serverAddr, i_targetPort);  // this is hanging if the port isn't open on the host (PC app not 'listening')...use a method where you can specify a timeout instead
            Socket socket = new Socket();
            InetSocketAddress addr = new InetSocketAddress(serverAddr, i_targetPort);
            socket.connect(addr, 2000);
            
                String message = scanResult.getContents(); 
                try { 
                    PrintWriter out = new PrintWriter( new BufferedWriter( 
                         new OutputStreamWriter(socket.getOutputStream())),true); 
                     
                    out.println(message); 
                    
                    // get 'ack'
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
                    String str = in.readLine();
                    
                    if(!str.equals("ack")){
                      resultsLogTextView.setText("failed to get \"ack\" from PC");
                        return;
                    }
                     
                } catch(Exception e) { 
                    resultsLogTextView.setText(e.getMessage());
                    return;
                } finally { 
                     socket.close(); 
                } 
              } catch (Exception e) { 
                  resultsLogTextView.setText("Error connecting to host PC: " + e.getMessage() + ".  Did you click *Listen*?");
                return;
              }
              
              //resultsLogTextView.setText(/*existingLog + "\n*/"scanned: " + scanResult.getContents());
              
              String barcodeType = " (" + scanResult.getFormatName() + ")"; 
              resultsLogTextView.setText(/*existingLog + "\n*/"scanned: " + scanResult.getContents() + barcodeType);
              
              if(continuousScanMode){  // scan again (user clicks 'back' button to break scanning loop)
                // launch ZXing to scan the barcode 
                  // (note that this will prompt them to install ZXing if it isn't installed yet)          
                  IntentIntegrator.initiateScan(PC_BCR.this, desiredCodeTypes); // scans specified barcode types
              }
        }       
    }    
    
    
    final int CODETYPES_ID = 0;
    final int SCANMODE_ID = 1;
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
      //super.onCreateOptionsMenu(menu);
      super.onPrepareOptionsMenu(menu);
      menu.clear();
      
      menu.add(0, CODETYPES_ID, 0, "Select Code Types");
      if(!continuousScanMode)
        menu.add(0, SCANMODE_ID, 0, "Use Continuous Scan Mode");
      else
        menu.add(0, SCANMODE_ID, 0, "Use Normal Scan Mode");
      
      return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
        case CODETYPES_ID: {
          Intent intent = new Intent(PC_BCR.this, SelectCodeTypes.class);
          intent.putExtra("activeCodeTypes", desiredCodeTypes);
            startActivityForResult(intent, SelectCodeTypes.SELECT_CODE_TYPES_REQUESTCODE);
            break;
        }
        case SCANMODE_ID: {
          continuousScanMode = !continuousScanMode;  // toggle the mode (continuous or normal)
        }
      }
      return super.onOptionsItemSelected(item);
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.