PHP for Android

dialogGetInput

postado em 27 de jun de 2012 17:02 por Silvio Garbes

 String title[optional, default Value]: title of the input box,
 
String message[optional, default Please enter value:]: message to display      
above the input box
,
 
String defaultText[optional]: text to insert into the input box)

Queries the user for a text input.

Exemplo:

  $droid->dialogGetInput("dialogGetInput","pergunta","conteudo");
  print_r($droid->dialogGetResponse());

dialogCreateInput

postado em 27 de jun de 2012 17:01 por Silvio Garbes

dialogCreateInput(
 
String title[optional, default Value]: title of the input box,
 
String message[optional, default Please enter value:]: message to display      
above the input box
,
 
String defaultText[optional]: text to insert into the input box,
 
String inputType[optional]: type of input data, ie number or text)

Create a text input dialog.

Exemplo:

  $droid->dialogCreateInput("dialogCreateInput","pergunta","conteudo");
  $droid->dialogSetPositiveButtonText("OK");
  $droid->dialogShow();
  print_r($droid->dialogGetResponse());


dialogCreateSpinnerProgress

postado em 26 de jun de 2012 17:18 por Silvio Garbes   [ 26 de jun de 2012 17:21 atualizado‎(s)‎ ]

dialogCreateSpinnerProgress(
 
String title[optional],
 
String message[optional],
 
Integer maximum progress[optional, default 100])

Create a spinner progress dialog.


Exemplo

$droid->dialogCreateSpinnerProgress("Recebendo dados do GPS...", "Por favor aguarde", 2000);
$droid->dialogShow();
sleep(15);
$droid->dialogDismiss();

dialogSetPositiveButtonText

postado em 25 de jun de 2012 18:24 por Silvio Garbes

dialogSetPositiveButtonText(
 
String text)

Set alert dialog positive button text.

Exemplo:

<?php 

    require_once("Android.php"); 
    $droid = new Android(); 

    $action = "start"; 
    while (true) { 

        switch($action) { 
            case "start": 
                $droid->dialogCreateAlert("Useful Numbers","Need a phone number?"); 

                $droid->dialogSetPositiveButtonText("My number"); 
                $droid->dialogSetNegativeButtonText("Family numbers"); 

                $droid->dialogShow(); 

                // Wait for user input 
                $result = $droid->dialogGetResponse(); 

                switch ($result['result']->which) { 
                    case "negative": 
                        $action = "family"; 
                    break; 
                    case "positive": 
                    default: 
                        $action = "my_number"; 
                    break; 
                } 
                $droid->dialogDismiss(); 
            break; 

            case "my_number": 
                $droid->dialogCreateAlert("My Number","My phone number is\n\n 01234 567890"); 

                $droid->dialogSetPositiveButtonText("back"); 
                $droid->dialogSetNegativeButtonText("exit"); 

                $droid->dialogShow(); 

                // Wait for user input 
                $result = $droid->dialogGetResponse(); 

                switch ($result['result']->which) { 
                    case "negative": 
                        $action = "bye"; 
                    break; 
                    case "positive": 
                    default: 
                        $action = "start"; 
                    break; 
                } 
                $droid->dialogDismiss(); 
            break; 

            case "family": 
                $droid->dialogCreateAlert("Choose people:"); 
                $list = array("My lovely wife","Home","Mum and Dad","Brother","Sister","Mum (mobile)"); 
                $phone_numbers = array("01234 567890","01234 567890", "01234 567890", "01234 567890", "01234 567890", "01234 567890"); 
                $n=0; 
                while($n<sizeof($list)+1) {$number[$list[$n]]=$phone_numbers[$n];$n++;} 
                $droid->dialogSetMultiChoiceItems($list); 
                $droid->dialogSetPositiveButtonText("Show numbers"); 
                $droid->dialogSetNegativeButtonText("Back"); 
                $droid->dialogShow(); //Display our dialog 
                $yesNo = $droid->dialogGetResponse(); 
                if ($yesNo['result']->which == "positive"){ 
                    $result = $droid->dialogGetSelectedItems(); 
                    $droid->dialogCreateSpinnerProgress("Retrieving information...","Please wait"); 
                    $droid->dialogShow(); 
                    unset($output); 
                    foreach ($result['result'] as $item){ 
                        $output[]=$list[$item]." - ".$number[$list[$item]]; 
                    } 
                    $output[]="[Back]"; 
                    $droid->dialogDismiss(); 
                    $droid->dialogCreateAlert("Your Numbers (click to call):"); 
                    $droid->dialogSetItems($output); 
                    $droid->dialogShow(); 
                    $res2 = $droid->dialogGetResponse(); 
                    $response = $output[$res2['result']->item]; 
                    if($response=="[Back]") {} 
                    else { 
  
$tel="tel:".substr($response,strpos($response,"-")+1,strlen($response)); 
                        $droid->startActivity("android.intent.action.VIEW",$tel); 
                        $droid->exit(); 
                        exit(); 
                        } 
                    $action = "start"; 
                    break; 
                }else{ 
                    $action = "start"; 
                    break; 
                } 
            break; 

            case "bye": 
                $droid->makeToast("Farewell!"); 
                $droid->exit(); 
                exit(); 
            break; 
        } 

    } 

?>

startActivity

postado em 25 de jun de 2012 17:54 por Silvio Garbes   [ 28 de jun de 2012 07:45 atualizado‎(s)‎ ]

startActivity(
 
String action,
 
String uri[optional],
 
String type[optional]: MIME type/subtype of the URI,
 
JSONObject extras[optional]: a Map of extras to add to the Intent,
 
Boolean wait[optional]: block until the user exits the started activity,
 
String packagename[optional]: name of package. If used, requires classname to  
be useful
,
 
String classname[optional]: name of class. If used, requires packagename to be
useful
)

Starts an activity.


Exemplo:


This launch the set wallpaper app. 
<?php 
         require_once("Android.php"); 
         $droid = new Android(); 
         $droid->startActivity("android.intent.action.SET_WALLPAPER"); 
         $droid->exit(); 
?> 

----------

And this get the power usage summary app. 
<?php 
        require_once("Android.php"); 
        $droid = new Android(); 
        $droid- 
>startActivity("android.intent.action.POWER_USAGE_SUMMARY"); 
        $droid->exit(); 
?>

---------------

print_r($droid->startActivity("android.intent.action.VIEW","tel:"));
print_r($droid->startActivity("android.intent.action.VIEW","tel:123"));
print_r($droid->sendEmail('',"assunto","teste"));

print_r($droid->startActivity("android.intent.action.VIEW","sms:"));
print_r($droid->startActivity("android.intent.action.VIEW","sms:123"));
print_r($droid->startActivity("android.intent.action.VIEW","smsto:123"));
$arr = array("sms_body" => "teste");
print_r($droid->startActivityForResult("android.intent.action.VIEW",null,"vnd.android-dir/mms-sms",$arr));
print_r($droid->startActivity("android.intent.action.VIEW",NULL,"vnd.android-dir/mms-sms",$arr));

print_r($droid->startActivity("android.intent.action.VIEW","mailto:"));
print_r($droid->startActivity("android.intent.action.VIEW","mailto:silviogarbes@gmail.com"));
print_r($droid->startActivity("android.intent.action.INSERT","content://contacts/people"));

-----------

$html = "<html><body>
<h1>Battery Status</h1>
<ul>
<li><strong>Status: s</li>
<li><strong>Temperature: s</li>
<li><strong>Level: s</li>
<li><strong>Plugged In: s</li>
</ul>
</body></html>";

$arquivo = '/sdcard/sl4a/scripts/battstats.html';
$fp = fopen($arquivo, 'w');
fwrite($fp, $html);
fclose($fp);

$droid->startActivity("android.intent.action.VIEW", "file:///sdcard/sl4a/scripts/battstats.html", "text/html");

-----------------

ExtensionMIME Type
Android Application.apkapplication/vnd.android.package-archive
Text.txttext/plain
.csvtext/csv
.xmltext/xml
Web related.htmtext/html
.htmltext/html
.phptext/php
Image.pngimage/png
.gifimage/gif
.jpgimage/jpg
.jpegimage/jpeg
.bmpimage/bmp
Audio.mp3audio/mp3
.wavaudio/wav
.oggaudio/x-ogg
.midaudio/mid
.midiaudio/midi
.amraudio/AMR
Video.mpegvideo/mpeg
.3gpvideo/3gpp
Package.jarapplication/java-archive
.zipapplication/zip
.rarapplication/x-rar-compressed
.gzapplication/gzip

-----------------


readSensors

postado em 25 de jun de 2012 17:03 por Silvio Garbes   [ 27 de jun de 2012 18:20 atualizado‎(s)‎ ]

readSensors()

Returns the most recently recorded sensor data.
Exemplo:

<?php
require_once("Android.php");
$droid = new Android();

// -----------------

$droid->startSensingTimed(1, 250);
sleep(5);

// Todos os sensores
echo "sensorsReadAccelerometer\n";
print_r($droid->readSensors());

//Posicao do celular
echo "sensorsReadAccelerometer\n";
print_r($droid->sensorsReadAccelerometer());

// Campo magnetico
echo "sensorsReadMagnetometer\n";
print_r($droid->sensorsReadMagnetometer());

// Bussola
echo "sensorsReadOrientation\n";
print_r($droid->sensorsReadOrientation());

$droid->stopSensing();

// --------------------

print_r($droid->startLocating());
sleep(15);

// GPS - Localizacao Atual
echo "readLocation\n";
$gps = $droid->readLocation();
print_r($gps);

// GPS - Ultima Localizacao
echo "getLastKnownLocation\n";
$gps1 = $droid->getLastKnownLocation();
print_r($gps1);

// GPS - Cidade, endereco
echo "geocode()\n";
print_r($droid->geocode($gps1['result']->gps->latitude,$gps1['result']->gps->longitude));


$droid->stopLocating();



// --------------------

/*

//Posicao do celular
sensorsReadAccelerometer
  [0] readSensors[xforce] => -0.61291564
  [1] readSensors[yforce] => 1.3790601
  [2] readSensors[zforce] => 9.193734

// Campo magnetico
sensorsReadMagnetometer
  [0] readSensors[xMag] => 8.0078125
  [1] readSensors[yMag] => -16.015625
  [2] readSensors[zMag] => 14.2578125

// Bussola
sensorsReadOrientation
  [0] readSensors[azimuth] => -2.6777017116547
  [1] readSensors[pitch] => -0.14856500923634
  [2] readSensors[roll] => 0.066568158566952

  http://developer.android.com/reference/android/hardware/SensorListener.html
    values[0]: Azimuth, rotation around the Z axis (0<=azimuth<360). 0 = North, 90 = East, 180 = South, 270 = West
    values[1]: Pitch, rotation around X axis (-180<=pitch<=180), with positive values when the z-axis moves toward the y-axis.
    values[2]: Roll, rotation around Y axis (-90<=roll<=90), with positive values when the z-axis moves toward the x-axis.

*/


?>

wifiStartScan

postado em 6 de jun de 2012 16:35 por Silvio Garbes

wifiStartScan()

Starts a scan for Wifi access points.

Returns:
 
True if the scan was initiated successfully.

Exemplo

<?php
/* @author: Nicolas B. <amd3002[at]gmail[dot]com> */
require_once('Android.php');
$droid = new Android();

/* First dialog box */
$droid->dialogCreateAlert('PFA Wifi Scanner','Welcome in PFA Wifi Scanner');
$droid->dialogSetNeutralButtonText('Ok');
$droid->dialogShow();
$droid->dialogGetResponse();//We wait until user press 'Ok'
$todo = 'init';

/* Main loop */
while (1)
{
   switch($todo)
   {
      case 'init':
         $droid->dialogCreateAlert('Menu', 'Make your choice...');
         $droid->dialogSetPositiveButtonText('Scan !');
         $droid->dialogSetNegativeButtonText('Exit');
         $droid->dialogShow();
         $choice = $droid->dialogGetResponse();//We wait until user press a button

         /* We test user choice */
         switch($choice['result']->which)
         {
            case 'positive' :
               /* We check if wifi is ON */
               $wifi_status = $droid->checkWifiState();
               if ($wifi_status['result'])
               {
                  /* Wifi is ON, we start scanning */
                  $droid->wifiStartScan();
                  $scan = $droid->wifiGetScanResults();
                  $ap_list = $scan['result'];

                  $droid->dialogCreateAlert('PFA Wifi Scanner');

                  /* We build an array based on the result of the scan */
                  $tab = array();
                  for ($i = 0 ; $i <= count($ap_list) - 1 ; $i++)
                  {
                     $line = '';
                     foreach($ap_list[$i] as $k => $v)
                     {
                        switch($k)
                        {
                           case 'ssid' :
                              $line .= $v . ' ';
                              break;

                           case 'capabilities' :
                              $line .= substr($v, 1, -1) . ' ';
                              break;

                           case 'level' :
                              $line .= $v . 'dbm ';
                              break;

                        }
                     }
                     $tab[$i] = $line;
                  }
                  /* We check if there is at least 1 AP found */
                  if (empty($tab[0]))
                  {
                     $tab[0] = 'No AP found !';
                  }
                  $droid->dialogSetItems($tab);
                  $droid->dialogShow();

                  /* We show result until user click his screen */
                  $droid->dialogGetResponse();
               }
                else//Wifi is OFF
                {
                  $droid->dialogCreateAlert('Error', 'Wifi is currently OFF, would you like to turn it ON ?');
                  $droid->dialogSetPositiveButtonText('Yes');
                  $droid->dialogSetNegativeButtonText('No');
                  $droid->dialogShow();
                  $choice = $droid->dialogGetResponse();//We wait until user press a button

                  /* We test user choice */
                  switch($choice['result']->which)
                  {
                     case 'positive' :
                        /* We try to turn wifi ON */
                        $wifi_status = $droid->toggleWifiState();
                        if (!$wifi_status['result'])
                        {
                           $droid->dialogCreateAlert('Error', 'An error occured, try to manually turn wifi ON...');
                           $droid->dialogSetNeutralButtonText('Ok');
                           $droid->dialogShow();
                           $droid->dialogGetResponse();//We wait until user press a button
                        }
                        break;

                     default :
                        break;
                  }
                }
               break;

            default ://Exit case
               $todo = 'exit';
               break;
         }
         break;

      case 'exit'://Exit case
         $droid->exit();
         exit(1);
         break;
   }
}
/* End of file */
?>

smsGetMessageIds

postado em 6 de jun de 2012 16:34 por Silvio Garbes

smsGetMessageIds(
 
Boolean unreadOnly,
 
String folder[optional, default inbox])

Returns a List of all message IDs.

Exemplo

<?php
/* @author: Nicolas B. <amd3002[at]gmail[dot]com>

Find more scripts on my blog : http://boutetnico.wordpress.com/

*/
require_once('Android.php');
$droid = new Android();

$DEFAULT_LIMIT = 10; /* Default SMS list length */
$todo = 'init';

/* Main loop */
while (1)
{
   switch($todo)
   {
      case 'init':
         /* Main menu */
         $droid->dialogCreateAlert('PFA SMS Infos');
         $droid->dialogSetPositiveButtonText('Show infos!');
         $droid->dialogSetNegativeButtonText('Exit');
         $droid->dialogShow();
         $choice = $droid->dialogGetResponse();/* We wait until user press a button */

         /* We test user choice */
         switch($choice['result']->which)
         {
            case 'positive' :

               /* We get number of SMS */
               $unread_SMS = $droid->smsGetMessageCount(1);
               $total_SMS = $droid->smsGetMessageCount(0);

               /* We extract values */
               $unread_SMS_result = $unread_SMS['result'];
               $total_SMS_result = $total_SMS['result'];

               /* SubMenu */
               $droid->dialogCreateAlert('PFA SMS Infos');
               $table[0] = 'Unread only : ' . $unread_SMS_result;
               $table[1] = 'Read & unread : ' . $total_SMS_result;

               $droid->dialogSetSingleChoiceItems($table);
               $droid->dialogSetPositiveButtonText('Show list');
               $droid->dialogSetNegativeButtonText('Exit');
               $droid->dialogShow();
               $response = $droid->dialogGetResponse();/* We wait until user press 'Back' or an entry in the list */

               switch($response['result']->which)
               {
                  case 'positive':/* Show list case */
                     $selected = $droid->dialogGetSelectedItems();

                     switch($selected['result'][0])/* Bi - dimensionnal array, 0 because it's first and unique value (SingleChoiceItems) */
                     {
                        case '0': /* Unread SMS only */
                           $ids = $droid->smsGetMessageIds(1);/* Retrieves a list of SMS's ids */
                           $amount = $unread_SMS_result;/* We need this in order to know how many SMS we will have to display */
                           break;

                        default: /* Everything else */
                           $ids = $droid->smsGetMessageIds(0);/* Retrieves a list of SMS's ids */
                           $amount = $total_SMS_result;/* We need this in order to know how many SMS we will have to display */
                           break;
                     }

                     /* If there are more SMS to display than the DEFAULT_LIMIT value, we ask user to input a limit */
                     if ($amount > $DEFAULT_LIMIT)
                     {
                        $howMany = $droid->getInput('PFA SMS Infos', 'How many SMS do you want to display [default = ' . $DEFAULT_LIMIT . '] ?');
                        if (!empty($howMany['result']))
                        {
                           $limit = $howMany['result'];
                        }
                        else
                        {
                           $limit = $DEFAULT_LIMIT;
                        }
                     }
                     else
                     {
                        $limit = $DEFAULT_LIMIT;
                     }

                     /* Infos we wanna extract from each SMS */
                     $attributes = array('body');

                     /* For each SMS id, we retrieve its content (body) */
                     $SMS_list = array();
                     $i = 0;
                     foreach($ids['result'] as $v)
                     {
                        $SMS = $droid->smsGetMessageById($v, $attributes);
                        $SMS_list[$i] = $SMS['result']->body;
                        $i++;

                        /* We display only a limited number of SMS */
                        if ($i >= $limit)
                           break;
                     }

                     /* We check if there is at least 1 SMS, if not we put a message in the array */
                     if (empty($SMS_list))
                        $SMS_list[0] = 'Nothing...';

                     $droid->dialogCreateAlert('PFA SMS Infos');
                     $droid->dialogSetItems($SMS_list);
                     $droid->dialogSetNeutralButtonText('Back');
                     $droid->dialogShow();
                     $droid->dialogGetResponse();/* We wait until user press 'Back' or an entry in the list */
                     break;

                  default :/* Exit case */
                     $todo = 'exit';
                     break;
               }
               break;

            default :/* Exit case */
               $todo = 'exit';
               break;
         }
         break;

      case 'exit'://Exit case
         $droid->exit();
         exit(1);
         break;
   }
}
/* End of file */
?>

cameraCapturePicture

postado em 6 de jun de 2012 16:31 por Silvio Garbes

cameraCapturePicture(
 
String targetPath,
 
Boolean useAutoFocus[optional, default true])

Take a picture and save it to the specified path.

Returns:
 A map of
Booleans autoFocus and takePicture where True indicates success.

Exemplo

<?
require_once("Android.php");
try {
   $droid = new Android();
   $droid->cameraCapturePicture("/sdcard/DCIM/ScriptPic.jpg");
} catch(Exception $e) {

        $droid->vibrate();
        $droid->notify('Exception',$e->getMessage());
        die("script exited with an exception");
}

?>

geocode

postado em 6 de jun de 2012 16:30 por Silvio Garbes

geocode(
 
Double latitude,
 
Double longitude,
 
Integer maxResults[optional, default 1]: maximum number of results)

Returns a list of addresses for the given latitude and longitude.

Returns:
  A list of addresses
.

Exemplo

<?php
// @author: Anton Perkin (anton.perkinAT_NOSP_AMgmail.com)
// http://groups.google.com/group/php-for-android/browse_thread/thread/bab685d3ae202152

include("Android.php");
$droid = new Android();

//creates alert
$droid->dialogCreateAlert();

$result = array();

//gets coordinates
$latitude = $droid->getInput("Location", "Latitude: ");
$longitude= $droid->getInput("Location", "Longitude: ");

//gets the location info
$locations = $droid->geocode($latitude['result'], $longitude['result']);

//parses location info
foreach ($locations['result'] as $location)
{
  $location = get_object_vars($location);

  //sets location items
  foreach ($location as $key => $value)
  {
    $result[] = ucfirst(str_replace('_', ' ', $key)).': '.$value;
  }
}
$droid->dialogSetItems($result);

//displays the box
$droid->dialogShow();

?>

1-10 of 14