I would definitely suggest using Google Cloud Messaging
here. This has the benefit that once a device runs your app, you can make it register against GCM
and you can send them the messages as needed, this way you don't have to struggle with sockets that close after a certain amount of time.
This approach would need that you have to implement some server (for instance, a web server with PHP) and make the users communicate with it, so the flow would be:
Your server sends a broadcast message to all registered devices telling them they have to register against the
GCM
service.The devices get the message, and you implement the
BroadcastReceiver
to get both latitude and longitude and send it to your remote server, sayhttp://www.mysuperserver.com/getmsg.php
, via aPOST
request.Your server processes the parameters and you save them or do whatever you need.
If you want to follow this approach, this are the steps you have to follow:
Go to https://console.developers.google.com. With your Google account, register a new project. This will provide you an API key and a Sender ID.
You'll need to make the device register against your project in
GCM
. You can achieve this by importingGoogle Play Services
within your project, and once done, do something alike to this:GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); final String regid = gcm.register("YOUR_SENDER_ID");
At this time, the
GCM
server already knows that this user has registered whithin your project and has given him aregid
.The next step is informing your own remote server that the user has done so, and save somewhere the
regid
that it has been given, so you can later send them messages. So in the client side, make aHTTP POST
request against your server sending thatregid
and process it with somethat like this:$regid = $_POST['regid']; if (($regId) && ($ipAddr)) sql_query("INSERT INTO gcm_subscribers(regid) VALUES($regid')");
Once done, you know who have already registered against your database. You can
SELECT
all the users and send them the new messages (simulating a multicast behavior).function sendNotification($registrationIdsArray, $messageData) { $apiKey = "YOUR_API_KEY"; $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey); $data = array( 'data' => $messageData, 'registration_ids' => $registrationIdsArray ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" ); curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) ); $response = curl_exec($ch); curl_close($ch); return $response; }
Once in your client, just process that
GCM
message and display it accordingly. To process the messages I'm including a few links below.
More about this: