// Plik CH4ExamplesActivity.java, część 1. z 7    
package ch4.example.proArduino;
  import java.io.FileDescriptor;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  // komponenty urządzenia Android
  import android.app.Activity;
  import android.app.PendingIntent;
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.content.IntentFilter;
  import android.os.Bundle;
  import android.os.ParcelFileDescriptor;
  import android.util.Log;
  import com.android.future.usb.*;
  // komponenty interfejsu użytkownika 
  import android.view.View;
  import android.widget.ToggleButton;
    
// Plik CH4ExamplesActivity.java, część 2. z 7

public class CH4ExamplesActivity  extends Activity   {  
   // deklaracje wejścia i wyjścia ADK
   UsbAccessory ARDUINO_ADK; // obiekt akcesorium
   ParcelFileDescriptor ADKstreamObj;
   FileInputStream ReciveFromADK;
   FileOutputStream SendtoADK;
   // konfiguracja i logowanie
   private static final String ACTION_USB_PERMISSION = "MEGA_ADK.USB_PERMISSION";
   private static final String TAG = "MEGA ADK"; // tag debugujący do logu
   private UsbManager UsbManagerOBJ;
   private PendingIntent Needed_Permission;
   private boolean IsPermissionNeeded;
   // komponenty interfejsu użytkownika
   private ToggleButton buttonLED;
       
// Plik CH4ExamplesActivity.java, część 3. z 7

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setupAccessory();
   setContentView(R.layout.main);
   registerUIobjects();
} // koniec onCreate
@Override
public void onDestroy() {
   unregisterReceiver(ADKReceiver);
   super.onDestroy();
} // koniec onDestroy

@Override
public void onPause() {
   super.onPause();
   closeAccessory();
} // koniec onPause() 
@Override
public void onResume() {
   super.onResume();
    if (ReciveFromADK != null && SendtoADK != null) {
      return;
     } // koniec if (ReciveFromADK != ...
   UsbAccessory[] accessories = UsbManagerOBJ.getAccessoryList();
   UsbAccessory accessory = (accessories == null ? null : accessories[0]);
    if (accessory != null) {
     if (UsbManagerOBJ.hasPermission(accessory)) {
       openAccessory(accessory);
     } // koniec if (UsbManagerOBJ.hasPermission(accessory))
     else {
      synchronized (ADKReceiver) {
       if (IsPermissionNeeded == true) {
         UsbManagerOBJ.requestPermission(accessory, Needed_Permission);
         IsPermissionNeeded = false;
       } // koniec if (IsPermissionNeeded == true)
      } // koniec synchronized ADKReceiverr)
     } // koniec else for if (UsbManagerOBJ...
    } // koniec if (accessory != null)
    else {
      Log.d(TAG, "zmienna accessory ma wartosc null");		
    } // koniec else if (accessory != null)
} // koniec onResume()

// Plik CH4ExamplesActivity.java, część 4. z 7

private BroadcastReceiver ADKReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
     if (ACTION_USB_PERMISSION.equals(action) == true) {
       synchronized (this) {
        UsbAccessory accessory = UsbManager.getAccessory(intent);
         if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
           openAccessory(accessory);
         }
         else {
           Log.d(TAG, "brak uprawnien dla akcesorium "+ accessory);
         }
        IsPermissionNeeded = true;
       } // koniec synchronized (this)
     }  // koniec if (ACTION_USB_PERMISSION.equals...
     else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
       UsbAccessory accessory = UsbManager.getAccessory(intent);
        if (accessory != null && accessory.equals(ARDUINO_ADK)) {
          closeAccessory();
        }
     } // koniec else if (UsbManager...
 } // koniec void onReceive(Context contex ...
}; // koniec private BroadcastReceiver..
@Override
public Object onRetainNonConfigurationInstance() {
   if (ARDUINO_ADK != null) {
     return ARDUINO_ADK;
   }
   else {
      return super.onRetainNonConfigurationInstance();
   }
} // koniec public Object onRetainNon*...

// Plik CH4ExamplesActivity.java, część 5. z 7

private void openAccessory(UsbAccessory accessory) {
   ADKstreamObj = UsbManagerOBJ.openAccessory(accessory);
    if (ADKstreamObj != null) {
      ARDUINO_ADK = accessory;
      FileDescriptor fd = ADKstreamObj.getFileDescriptor();
      ReciveFromADK = new FileInputStream(fd);
      SendtoADK = new FileOutputStream(fd);
      Log.d(TAG, "akcesorium otwarte");
    } // end if (ADKstreamObj
    else {
      Log.d(TAG, "błąd otwarcia akcesorium");
    }
} // koniec void openAccessory...

private void setupAccessory() {
   UsbManagerOBJ = UsbManager.getInstance(this);
   Needed_Permission = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
   IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
   filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
   registerReceiver(ADKReceiver, filter);
    if (getLastNonConfigurationInstance() != null) {
    	ARDUINO_ADK = (UsbAccessory) getLastNonConfigurationInstance();
      openAccessory(ARDUINO_ADK);
   }
} // koniec private void setupAccessory()

private void closeAccessory() {
   try {
    if (ADKstreamObj != null) {
      ADKstreamObj.close();
    }
   } // koniec try
   catch (IOException e) {
	   Log.e(TAG, "Wyjątek IO", e);
   } 
   finally {
     ADKstreamObj = null;
     ARDUINO_ADK = null;
   } // koniec wszystkich try catch finally
} // koniec private void closeAccessory()

// Plik CH4ExamplesActivity.java, część 6. z 7

private void write(byte[] send){
   if (SendtoADK != null) {
      try {
        SendtoADK.write(send);
      }
      catch (IOException e){ 
        Log.e(TAG, "błąd zapisu", e);
      }
   } // koniec if (SendtoADK != null)
} // koniec private void write...

// Plik CH4ExamplesActivity.java, część 7. z 7

private void registerUIobjects(){
   buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLED);
}
public void blinkLED(View v) {
   byte[] BytestoSend = new byte[1];
    if (buttonLED.isChecked())
      BytestoSend[0] = (byte) 1; // przycisk pokazuje bieżący stan diody włączony
    else
      BytestoSend[0] = (byte) 0; // przycisk pokazuje bieżący stan diody wyłączony
    write(BytestoSend); // wysłanie bajtu do ADK
} // koniec void blinkLED(View v)
} // koniec public class CH4ExamplesActivity
