2011-01-07 9 views
7

Attualmente ho una parte di codice nella mia applicazione Android che preleva i dispositivi IMEI e invia l'IMEI come parametro a uno script PHP che è ospitato su Internet.Invio di una risposta da PHP a un'app mobile Android/Java?

Lo script PHP quindi accetta il parametro IMEI e controlla un file per vedere se l'IMEI esiste nel file, se lo fa voglio essere in grado di consentire alla mia applicazione Android di sapere che l'IMEI esiste. Quindi in sostanza voglio solo essere in grado di restituire True alla mia applicazione.

È possibile utilizzare PHP?

Ecco il mio codice finora:

Android/Java

//Test HTTP Get for PHP 

     public void executeHttpGet() throws Exception { 
      BufferedReader in = null; 
      try { 
       HttpClient client = new DefaultHttpClient(); 
       HttpGet request = new HttpGet(); 
       request.setURI(new URI("http://testsite.com/" + 
         "imei_script.php?imei=" + telManager.getDeviceId() 
         )); 
       HttpResponse response = client.execute(request); 
       in = new BufferedReader 
       (new InputStreamReader(response.getEntity().getContent())); 
       StringBuffer sb = new StringBuffer(""); 
       String line = ""; 
       String NL = System.getProperty("line.separator"); 
       while ((line = in.readLine()) != null) { 
        sb.append(line + NL); 
       } 
       in.close(); 
       String page = sb.toString(); 
       System.out.println(page); 
       } finally { 
       if (in != null) { 
        try { 
         in.close(); 
         } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 

È possibile che questo invia il codice IMEI come parametro allo script PHP che lo raccoglie con successo e viene eseguito un controllo contro il file con successo, tuttavia ho bisogno di essere in grado di inviare una risposta positiva dallo script PHP se l'IMEI ne soddisfa uno nel file.

Ecco il PHP:

<?php 
    // to return plain text 
    header("Content-Type: plain/text"); 
    $imei = $_GET["imei"]; 

    $file=fopen("imei.txt","r") or exit("Unable to open file!"); 

    while(!feof($file)) 
    { 
    if ($imei==chop(fgets($file))) 
    echo "True"; 
    } 

    fclose($file); 

?> 

Così, invece di eco Vero voglio essere in grado di lasciare la mia domanda sa che l'IMEI è stato trovato, è questo possibile ed in caso affermativo cosa dovrei essere usando per raggiungerlo?

risposta

3

questa è roba buona! in realtà, ci sei quasi. il tuo php non dovrebbe cambiare, il tuo java dovrebbe! hai solo bisogno di controllare il risultato della risposta all'interno del tuo codice java. ridichiarare il metodo di Java come

public String executeHttpGet() { 

allora, lasciate che questo metodo di restituire la pagina variabile.

ora è possibile creare un metodo di supporto da qualche parte. se lo metti nella stessa classe come executeHttpGet, che sarà simile a questa:

public boolean imeiIsKnown(){ 
    return executeHttpGet().equals("True"); 
} 

ora è possibile chiamare questo metodo per scoprire se il vostro IMEI è noto nel backend php.

+1

hmm ... forse il metodo imeiIsKnown dovrebbe restituire executeHttpGet(). StartsWith ("True"); o forse restituire executeHttpGet(). equals ("True" + System.getProperty ("line.separator")); – davogotland

+0

Grazie Ho semplicemente rimosso la nuova variabile di riga in modo che solo "Vero" venga restituito nella pagina delle variabili, grazie. Ora per iniziare a cercare di collegarlo ad un database :) –

+0

supponiamo nello scenario sopra chiesto che sono al termine php e il dispositivo Android si sta connettendo con me e prendendo una certa risposta. Ora c'è un modo in cui posso essere sicuro che la risposta abbia raggiunto l'applicazione Android. – jishan

2

Non sono sicuro che faccia bene o meno, ma è possibile utilizzare le intestazioni. Se l'IMEI è stato trovato, è possibile inviare un'intestazione ("Stato: HTTP/1.1 200 OK") altrimenti inviare l'intestazione ("Stato: 404 non trovato").

E quindi è necessario controllare lo stato della risposta nell'applicazione.

0

il tuo codice è fondamentalmente audio, tutto ciò che devi fare è modificarlo un po '. ho mescolato e abbinato le risposte sopra, perché avevo bisogno di realizzare esattamente quello che stavi cercando di fare. Ho creato un database, invece di controllare i file txt.

CREATE TABLE IF NOT EXISTS `user_device` (
    `Id_User_Device` int(11) NOT NULL auto_increment, 
    `Nr_User_Device` varchar(60) collate utf8_bin NOT NULL, 
    `Ic_User_Device_Satus` int(11) NOT NULL default '1', 
    PRIMARY KEY (`Id_User_Device`), 
    KEY `Nr_User_Device` (`Nr_User_Device`,`Ic_User_Device_Satus`) 
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=20 ; 

il codice java di Android sarebbe (non dimenticare di creare le regolazioni corrette nel principale.file di layout xml, l'inserimento di 2 elementi a uno schermo HelloWorld classica:

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.URI; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 

public class ZdeltestEMEIActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(this); 
     String deviceUuid = deviceUuidFactory.getDeviceUuid().toString(); 
     Log.d("tgpost",deviceUuid); 
     try { 
      String webPostAnswer = deviceIdCheck(deviceUuid); 
      if (webPostAnswer != null) { 
       TextView tv1 = (TextView) findViewById(R.id.textdisplay01); 
       TextView tv2 = (TextView) findViewById(R.id.textdisplay02); 
       tv1.setText(webPostAnswer); 
       tv2.setText(deviceUuid); 
       Log.d("tgpost", "okok "+webPostAnswer); 
      } else { 
       Log.d("tgpost", "nono empty"); 
      } 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      Log.i("tgpost", "exc " + e.getMessage()); 
      Log.i("tgpost", e.toString()); 
      Log.e("tgpost", e.getStackTrace().toString()); 
      e.printStackTrace(); 
     }   
    } 
    public String deviceIdCheck(String deviceUuidIn) throws Exception { 
     boolean flagOK = false; 
     BufferedReader in = null; 
     try { 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet request = new HttpGet(); 
      Log.v("tgpost", "okok"); 
      //"imei_script.php?deviceId="; + telManager.getDeviceId() 
      request.setURI(new URI("http://www.you.net/" + 
        "deviceIdCheck.php?deviceId=" + deviceUuidIn 
        )); 
      HttpResponse response = client.execute(request); 
      Log.d("tgpost", "php answered> "+response); 
      in = new BufferedReader 
      (new InputStreamReader(response.getEntity().getContent())); 
      StringBuffer sb = new StringBuffer(""); 
      String line = ""; 
      String NL = System.getProperty("line.separator"); 
      while ((line = in.readLine()) != null) { 
       sb.append(line + NL); 
      } 
      in.close(); 
      String page = sb.toString(); 
      Log.d("tgpost", "php answered HUMAN> "+page); 
      return page; 

     } catch (Exception e) { 
      return "problems with connection "+e.getMessage(); 
     } 
    } 
} 

con una classe supplementare

import android.content.Context; 
import android.content.SharedPreferences; 
import android.provider.Settings.Secure; 
import android.telephony.TelephonyManager; 
import java.io.UnsupportedEncodingException; 
import java.util.UUID; 

public class DeviceUuidFactory { 
    protected static final String PREFS_FILE = "device_id.xml"; 
    protected static final String PREFS_DEVICE_ID = "device_id";  
    protected static UUID uuid; 
    public DeviceUuidFactory(Context context) { 
     if(uuid ==null) { 
      synchronized (DeviceUuidFactory.class) { 
       if(uuid == null) { 
        final SharedPreferences prefs = context.getSharedPreferences(PREFS_FILE, 0); 
        final String id = prefs.getString(PREFS_DEVICE_ID, null); 
        if (id != null) { 
         // Use the ids previously computed and stored in the prefs file 
         uuid = UUID.fromString(id); 
        } else { 
         final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); 

         // Use the Android ID unless it's broken, in which case fallback on deviceId, 
         // unless it's not available, then fallback on a random number which we store 
         // to a prefs file 
         try { 
          if (!"9774d56d682e549c".equals(androidId)) { 
           uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")); 
          } else { 
           final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId(); 
           uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID(); 
          } 
         } catch (UnsupportedEncodingException e) { 
          throw new RuntimeException(e); 
         } 

         // Write the value out to the prefs file 
         prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString()).commit(); 

        } 

       } 
      } 
     } 

    } 


    /** 
    * Returns a unique UUID for the current android device. As with all UUIDs, this unique ID is "very highly likely" 
    * to be unique across all Android devices. Much more so than ANDROID_ID is. 
    * 
    * The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on 
    * TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back 
    * on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a 
    * usable value. 
    * 
    * In some rare circumstances, this ID may change. In particular, if the device is factory reset a new device ID 
    * may be generated. In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2 
    * to a newer, non-buggy version of Android, the device ID may change. Or, if a user uninstalls your app on 
    * a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation. 
    * 
    * Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT 
    * change after a factory reset. Something to be aware of. 
    * 
    * Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly. 
    * 
    * @see http://code.google.com/p/android/issues/detail?id=10603 
    * 
    * @return a UUID that may be used to uniquely identify your device for most purposes. 
    */ 
    public UUID getDeviceUuid() { 
     return uuid; 
    } 
} 

sul lato php:

<?php 
// to return plain text 
// header("Content-Type: plain/text"); 
include('/home/public_html/ConnStrDB.php'); 
$deviceId = $_GET["deviceId"]; 
$sql = "SELECT Nr_User_Device FROM user_device WHERE Nr_User_Device = '".$deviceId."'"; 
$result = mysql_query($sql); 
if ($result) { 
    $row = mysql_fetch_array($result); 
    if ($row[0]) {$deviceIdFile = $row[0];} else {$deviceIdFile = "device not found";} 
} else { 
    $deviceIdFile = "no check was made, empty set"; 
} 
echo $_GET["deviceId"]." ".$deviceIdFile; 
?> 

e (in modo che non dovete per inserire manualmente i numeri (basta modificare il file phpName nell'invio):

<?php 
// to return plain text 
// header("Content-Type: plain/text"); 
include('/home/public_html/ConnStrDB.php'); 
$deviceId = $_GET["deviceId"]; 
$sql = "SELECT Nr_User_Device, Ic_User_Device_Status FROM user_device WHERE Nr_User_Device = ".$deviceId; 

$sql = "INSERT INTO user_device (Nr_User_Device) VALUES ('".$deviceId."')"; 
$result = mysql_query($sql); 
if ($result) { 
    $deviceIdFile = "device inserted"; 
} else { 
    $deviceIdFile = "not inserted"; 
} 
echo $_GET["deviceId"]." ".$deviceIdFile; 
?> 

in caso di successo, il tuo schermo mobile visualizzerà le imei 3 volte (quella sul dispositivo, quella ricevuta in php e quella recuperata nel database).

ConnStrDB.php è un file che contiene la connessione completa al database MySQL.

se si risponde con un testo lungo, l'applicazione Android lo riceverà, così come la versione dettagliata di qualsiasi avviso php. se non hai bisogno di json, puoi rispondere a qualsiasi xml tramite php echo. Grazie per la tua domanda, molto utile! e grazie per le risposte ECCELLENTI!

Problemi correlati