I am making a location application, where user can parameter some function from the server, so I want the server to begin a communication with the phone of the user.
But firstly, I want to open a communication with an android, from the php.
Is there a way to communicate with an android phone from a php server?
I already use the communication from android with HTTP to server with return of JSONObject, but I cant find anything for a php call to android.
I think its exactly like the application which can make your phone ring.
Check out Google Cloud Messaging for Android.
Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device. This could be a lightweight message telling your app there is new data to be fetched from the server (for instance, a movie uploaded by a friend), or it could be a message containing up to 4kb of payload data (so apps like instant messaging can consume the message directly).
The GET method
You will need to have the Android client connect to your server and pass your JSON messages. If the client needs to get some data from the server and disconnect, then you can just use a normal HTTP type GET.
The WebSocket method
If however, you decide you need a long running TCP connection passing JSON bidirectionally then you should consider something like WebSockets. I have written an Android WebSocket demo. The Android client by default connects to the websocket.org echo server, but that can be easily changed.
I also found a PHP WebSockets implementation.
The Push Method
Now if your plan is to push messages from the server to the client without the client initiating the connection you will need something like GCM (Google Cloud Messaging). Here is an article covering GCM and PHP.
Generally, creating connection from server side to client side is complex, because:
The client might use private IP address.
Inbound connection might be rejected if the device connected behind firewall.
You need to install an application if that can be run in the background and watches the server for new messages.
Using Web:
It depends on the browser how it support JavaScript API especially new HTML5 features such as Server Sent Events
To enable servers to push data to Web pages over HTTP or using
dedicated server-push protocols, this specification introduces the
EventSource interface.
Please use below link for store data in mysql using php and u need to create webservice in that you will get two response from php server
1) Json
2) xml
if you show example please visit below link
Creating a basic web services in php
also visit this link for better description
http://phpmaster.com/lets-talk-1/
You Can Use HTTpReq class :
public class HttpReq {
public String send (String url){
//send a http request and get the result
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
Then you use this class to make connection and to call your php file to get the data as JSonObject .
ht = new HttpReq();
// send a http request with GET
x=ht.send("http://10.0.2.2/myFolder/myFile.php");
JSONArray jArray;
JSONObject json_data;
String h[]=x.split("<");
try {
jArray = new JSONArray(h[0]);
json_data = jArray.getJSONObject(0);
url=json_data.getString("url");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In Your Php file you may use this methods to get the JSon data or to send it to the android App
Json_decode($string);
And
Json_encode($string);
I hope that will help you :)
Related
I have a simple PHP web-service which return result as JSON .
if($_SERVER["REQUEST_METHOD"]=="POST"){
$arg1=$_POST["arg1"];
processArgs($arg1);
}
processArgs($arg1){
$result=doSomething($arg1);
echo json_encode($result);
}
I could call it from Android side using HttpURLConnection. But the problem is HttpURLConnection seems to be a work in very low level. Is there any level implementation which we could avoid writing the same code for making it asynchronous and for parsing the result.
Simply use HttpClient as follows.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://your-host/comm.php");
try {
//add your post data
List<NameValuePair> args = new ArrayList<NameValuePair>(2);
args.add(new BasicNameValuePair("arg1", "your-arg-1"));
httpPost.setEntity(new UrlEncodedFormEntity(args));
//send your request
HttpResponse response = httpClient.execute(httpPost);
} catch (ClientProtocolException | IOException e) {
e.printStackTrace();
}
HttpURLConnection (java.net.HttpURLConnection) is the default HTTP client in Android.
OkHttp, is another one which became the engine that powers HttpUrlConnection as of Android 4.4. It is offers easier method to customize each requests.
Both HttpURLConnection and OkHttp works at somewhat low level. So we need to write our own code for making it asynchronous and for parsing the result again and again.
Retrofit, on the other hand, is a high level implementation which uses OkHttp for connection and Gson for parsing result. It can be used to turn HTTP APIs into a Java interface with ease.
Therefore, Retrofit would be the best choice unless you have specific reason to go with OkHttp ( Like HTTP-based streaming).
I'm developping and android application and in some point I need to get some vaue from my server. This server has a simple PHP script that just echo a value.
In order to do it, that's what I do:
private static String executePHP(String URL) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
return(response);
} catch (IOException e) {
// TODO Auto-generated catch block
return("");
}
}
The method is static, because I call it upon an SMS arrives. Then the URL comes from the SMS text.
From the broadcastReceiver I call:
MainActivity.executePHP(link);
I want the execution of the PHP to be on a background task.
I've been reading of AsyncTask but they need and instance, which I don't have.
What's the best way to do it??
Also, have in mind that the application may not be active right now.
I'll be happy if I can only Toast the result from the PHP executing on asyncTask (or other asyncrhonus thread).
Thanks you all!!
Have a nice day!
Finally, this solve my question! Now I need to see how to handle no-internet-connection.
solution
I am making an Android App which interacts with remote server's database and communicate with each other by passing JSON object to and from.
I need to know how to write such a service on my server (preferably in PHP) to which the android app can make request and on receiving the request, the server processes and makes a JSON object and passes that to the android app.
Also, i need to know, when this service is running on the server, on WHICH URL will the android app make request?
For example, if android app have to request to sever to fetch data for parameters:
name: Apple
location: US
then, i guess the android app will have to request the server in form of:
www.example.com?name='Apple"&location='US'
So how to make such a service running on the remote server?
Thanks in advance !
The best example you can refer for this is http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/. It has complete code[php+ android] with simple explanation.
You can write a method that request remote php file that responses to post or get request. if you want to use post request , you can use method below. and you have to add Internet permisson to your manifest file. As you see below , you can add parameters as being key -value pair.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/webservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "Apple"));
nameValuePairs.add(new BasicNameValuePair("locaction", "US"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler <String> res=new BasicResponseHandler();
// Execute HTTP Post Request
String response = httpclient.execute(httppost,res);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
I'm going nuts! Maybe someone can help me?!
I have an sqlite-database on a running server, which I receive due to an php-script. (To make it clear: I'm calling an php-script which gives me the the database as a response). With the response I'm now trying to "parse" it to an regular *.db file which I later on use for my app.
the app works fine, while placing the *.db into the assets folder. But I need to get the updated database everytime when calling the app. Therefore I need to receive it somehow from the server.
Just for notice: I don't know why they use a php-script for that, but it works perfectly with the iOS-Version of the app. So I am 100% sure that the script does work.
Got any hints or a solution to that?
Thanks!
EDIT: here is what I'm trying to do.
private void copyDatabase() {
InputStream myInputDB = null;
OutputStream myOutputDB = null;
HttpResponse response = null;
// Path to the just created empty db
String dbFilePath = DB_PATH + KeyConstants.DB_NAME;
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://USERNAME:PASSWORD#ADRESS/u/db.php");
try {
response = httpClient.execute(httpPost);
//Open your local db as the input stream
myInputDB = response.getEntity().getContent();
//Open the empty db as the output stream
myOutputDB = new FileOutputStream(dbFilePath);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInputDB.read(buffer)) > 0){
myOutputDB.write(buffer, 0, length);
}
//Close the streams
myOutputDB.flush();
myOutputDB.close();
myInputDB.close();
} catch (IOException ioEXC) {
throw new Error("Problem copying database from resource file.");
}
What do You have the problem with? With the Android app or with the PHP script?
I don't understand why there is a whole DB file request-response and not just the data (and better in some lazy reading), but that's not matter of Your case.
If You need to "download" all the DB at every run You should call and implement some method to do so - in the very first Activity call this method within onCreate() method. You can create a simple method within this Activity or in better approach create a simple class for this that will be instanciated and its method called within the first activity's onCreate().
But maybe I just don't understand You question...
EDIT: try reading through this problem: Can I download an SQLite db on /sdcard and access it from my Android app?
I want the Android device to send data to a PHP server. After receiving, the PHP server sends other data to Android. The first part can be done by using JSON. However, I don't know how to make the PHP server sends data to Android. Sorry, I am new to PHP!
I'm currently developing application that's communicating with PHP server (two-way communication, server sends data to application and application sends data to server), in objective-c [for iphone], but principle is same I guess.
We've used REST service with JSON.
In your case, it should work like this:
Mobile 1 sends data via REST call to REST server (it calls method1. Server is developed, for example, using Zend_REST.), it stores data in Database (mySQL for example).
Mobile 2 periodically sends request to REST server, to a method which checks for new entries in mySQL. If there's something new, it sends response with data, if not - it sends false.
Whatever data is "printed" by your PHP script will be returned in the response to the call made on the Android device.
You can do something like this in PHP:
<?php
// TODO: Handle incoming data
// Send JSON data back to client
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// Compute data
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Encode/print data
echo json_encode($data);
?>
You would want to replace the first comment with your code to handle the data that was submitted from the client (Android). Then you set the response headers to be of type application/json and echo back your encoded data.
Technically you could echo/print back anything you would like, but using a format like JSON makes it much easier to decode the data on the client side.
Here is an Android snippet to send a POST request to some bogus website, sending email, password and a data string (you would put your json in the data string
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://website.com/yourPageHere.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", emailString));
nameValuePairs.add(new BasicNameValuePair("password", passwordString));
nameValuePairs.add(new BasicNameValuePair("data", yourDataString));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
//do stuff
}
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
//do stuff
} catch (IOException e) {
//do stuff
}
if(response == null){
//time out or other problem, fail gracefully
}
HttpEntity responseEntity = response.getEntity();
try {
String jsonString = EntityUtils.toString(responseEntity);
//jsonString is the full body of the response from the server
//if your php script is sending json, thats whats in here
} catch (ParseException e) {
//do stuff
} catch (IOException e) {
//do stuff
}
Your php script, yourPageHere.php
Treat this just like any other php script you might write, except instead of returning html you are just returning a chunk of text representing json data.
<?php
header('Content-type: application/json');
/*
here you can use the $_POST['email'], $_POST['password']
and $_POST['data'] indexes to access the data sent to
you from the phone, then create a json string to return
to the phone
*/
/* you can convert php objects/arrays to json using
json_encode($object), handle this however you
want just so that $jsonString is the final
representation of the json object */
$jsonString = 'blabla';
/*
prints the string in the body of the response,
this is the "jsonString" object found in the
above android snippet.
*/
echo $jsonString; //
?>
You can do the above with GET requests instead of POST too.
If you are really new to PHP you might want to make a couple form page samples to get the hang of reading url parameters.
What you're looking for is some sort of AJAX call, allowing the HTTP GET request to stick around and wait for the server return value:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/