How to perform network operation in AsyncTask - Android - android

I am new to Android and I am using the a button click to send a push notification using GCM. I have the function to perform the GCM push. I need it to be converted from the function to a AsyncTask class. I saw a lot from the internet and still facing trouble. Can anyone help me to convert it ?
The push function
public void sendPush(int position){
pushProgressBar.setVisibility = (View.VISIBLE)
try {
// Prepare JSON containing the GCM message content. What to send and where to send.
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put("message", "Hello");
// Where to send GCM message.
TinyDB tinyDB = new TinyDB(mContext);
ArrayList<String> userToken = tinyDB.getListString("tokenList");
String tokenToSend = userToken.get(position);
jGcmData.put("to", tokenToSend);
// What to send in GCM message.
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + R.string.apikey);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
// Read GCM response.
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
System.out.println("Check your device/emulator for notification or logcat for " +
"confirmation of the receipt of the GCM message.");
pushProgressBar.setVisibility = (View.GONE)
} catch (IOException e) {
System.out.println("Unable to send GCM message.");
System.out.println("Please ensure that API_KEY has been replaced by the server " +
"API key, and that the device's registration token is correct (if specified).");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance. Hope I learn from this.

Example basic AsyncTask:
class PushTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
pushProgressBar.setVisibility = (View.VISIBLE);
}
#Override
protected Integer doInBackground(Integer... position) {
int post = position[0];
int respCode = 0;
try {
//your sending code here..
//got gcm code
respCode = 1;
} catch (IOException e) {
//json IOException
//cannot send gcm
respCode = 2;
} catch (JSONException e) {
//json Exception
respCode = 3;
}
return respCode;
}
#Override
protected void onPostExecute(Integer response) {
switch(response)
case 1:
System.out.println("Check your device/emulator for notification or logcat for " +
"confirmation of the receipt of the GCM message.");
break;
case 2:
System.out.println("Please ensure that API_KEY has been replaced by the server " +
"API key, and that the device's registration token is correct (if specified).");
break;
case 3:
//print json Exception error
break;
default:
break;
pushProgressBar.setVisibility = (View.GONE);
}
}
You can execute the class by execute
new PushTask().execute(1 or your position);
This is example only, you can modified the code according your requirement.

Related

How to Handle connection timeout in async task

I have a problem that I haven't solved yet and I need help.
When internet is slow application crashes. how can can I check connection timeout in asyntask.
I made an app that sometimes connect to web service to get data and i do that using async task
I want to make alert dialog on connection timeout when user can choose whether they want to retry or cancel, if they choose retry it will try to connect again
public class login extends AsyncTask<Void,Void,Void> {
InputStream ins;
String status, result, s = null, data = "",js;
int ss;
int responseCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdlg.setTitle("Checking");
pdlg.setMessage("Please wait");
pdlg.setCancelable(false);
pdlg.show();
}
#Override
protected Void doInBackground(Void... params) {
StringBuilder sb = new StringBuilder();
ArrayList al;
try {
URL url = new URL("http://....login.php");
String param = "username=" + uname + "&password=" + pass;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bw.write(param);
bw.flush();
bw.close();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
}
data = sb.toString();
JSONObject json = new JSONObject(data);
status=json.getString("Status");//{"Login Status":"Success","Receipt Details":"No data available"}
// js=json.getString("Login");//{"Login":"Failed"}
} catch (MalformedURLException e) {
Log.i("MalformedURLException", e.getMessage());
} catch (IOException e) {
Log.i("IOException", e.getMessage());
} catch (JSONException e) {
Log.i("JSONException", e.getMessage());
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String status1=status.trim();
if (status1.equals("Success")) {
Toast.makeText(getApplicationContext(), "Login Succes !!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login.this, Home.class);
startActivity(i);
finish();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("first_time", false);
editor.putString("userrname", uname);
editor.putString("password",pass);
editor.apply();
Toast.makeText(getApplicationContext(),"welcome : "+uname,Toast.LENGTH_LONG).show();
}
else {
Toast t=Toast.makeText(Login.this, "Username or Password is Incorrect", Toast.LENGTH_LONG);
t.setGravity(Gravity.BOTTOM,0,0);
t.show();
}
pdlg.dismiss();
}
}
You can use getErrorStream() ,
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inp;
// if some error in connection
inp = connection.getErrorStream();
check this answer for more details..
according to the doc it returns
an error stream if any, null if there have been no errors, the
connection is not connected or the
server sent no useful data
.
use this two catch blocks to handle ConnectionTimeOut and socketTimeOut Exceptions
catch (SocketTimeoutException bug) {
Toast.makeText(getApplicationContext(), "Socket Timeout", Toast.LENGTH_LONG).show();
}
catch (ConnectTimeoutException bug) {
Toast.makeText(getApplicationContext(), "Connection Timeout", Toast.LENGTH_LONG).show();
}
For Connection time out add SocketTimeoutException in your catch block and its crashing because without null checking, you are trying to trim the string in onPostExecute
You should do like this, and check before using status
if(TextUtil.isEmpty(status)) {
pdlg.dismiss();
// We are getting empty response
return;
}
String status1=status.trim();
You can catch the Connection timeout exception in your code and then set the status according to your requirement and check for that status in onPostExecute to show the alert Dialog
try {
URL url = new URL("http://....login.php");
String param = "username=" + uname + "&password=" + pass;
// Your URL connection code here
catch (ConnectTimeoutException e) {
Log.e(TAG, "Timeout", e);
status="timeout"
} catch (SocketTimeoutException e) {
Log.e(TAG, " Socket timeout", e);
status="timeout"
}
in onPostExecute
if (status.equals("timeout")) {
// Show Alert Dialog.
}
What you are trying to do is previously done in some great networking lib. So I urge you to use one of the widley used network lib.
Volley.
Or if you want to understand you can just check the response status(or status code should be 408. I guess for connection time out) if it will return "connection time out" then you can call your code to the http client again to perform your task, you can also add a retry count to try for 2-3 times and then give up and send response to onpostexecute method.
Hope this helps.

POSt request to web API server (InputStream error in android studio)

I'm trying to add users' registeration data to a web api server but when I click on register button in UI after entering the data , the android monitor shows this error :
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
*this is my code :
----> the onClick function for registeration button :
public void register_register(View view) {
Name = name.getText().toString();
Email = email.getText().toString();
Password = password.getText().toString();
// make object from user to insert data
User user = new User(Name, Email, Password);
//convert data from user object to a json object
JSONObject jUser = new JSONObject();
JSONArray aUser = new JSONArray();
try {
jUser.put("Name", user.name);
jUser.put("Email", user.email);
jUser.put("Password", user.password);
//inserting JSON object inside JSON array
aUser.put(jUser);
Log.i("my Json object", jUser.toString());
Log.i("my Json array", aUser.toString());
String jsonData = aUser.toString();
new DoRegister().execute(jsonData);
//clear all edit texts
name.getText().clear();
email.getText().clear();
password.getText().clear();
} catch (JSONException e) {
e.printStackTrace();
}
}
-------> this is my posting class that extends from AsyncTask :
class DoRegister extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String jsonData = params[0];
try {
URL url = new URL(API);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
//send data
OutputStream dos = connection.getOutputStream();
dos.write(jsonData.getBytes());
//receive & read data response
InputStream is = connection.getInputStream();
String result = "";
int byteCharacter;
while ((byteCharacter = is.read()) != -1) {
result += (char) byteCharacter;
}
Log.i("my Json api" , "here :" + result);
is.close();
dos.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(getApplicationContext() , "Done" , Toast.LENGTH_SHORT).show();
}
}
------> This is what being shown in android monitor
java.io.FileNotFoundException: http://(my api here)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
at com.example.heshamadawy.registeration.RegisterActivity$DoRegister.doInBackground(RegisterActivity.java:102)
at com.example.heshamadawy.registeration.RegisterActivity$DoRegister.doInBackground(RegisterActivity.java:78)
Please help me and thank you guys :)
ok , I changed my code to Volley library and everything is okay right now ..
If you had the same problem try to use Volley , it's simple ,easy and better
best wishes for you all :)

Using Twitter Fabric to retrieve my own account tweets

I'm currently using twitter fabric framework and trying to retrieve the list of my own account tweets. I tried searching online to no avail. The example in the document shows how to display a tweet based on tweetID. I do not want that. I do understand that REST client makes a http connection with the supplied variables and to retrieve the JSON results back to parse and etc.
This are my current codes which upon successful login it will display another activity which i want my tweets to be shown here.
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
token = authToken.token;
secret = authToken.secret;
Log.i("token",token);
Log.i("secret",secret);
successNewPage();
}
I have also passed the token and secret key over to the next activity using intent
public void successNewPage(){
Intent intent = new Intent(this, LoginSuccess.class);
intent.putExtra("token",token);
intent.putExtra("secret", secret);
startActivity(intent);
}
On the new activity class, i followed their documentation and came out with this,
TwitterAuthConfig authConfig = new TwitterAuthConfig("consumerKey", "consumerSecret");
Fabric.with(this, new TwitterCore(authConfig), new TweetUi());
TwitterCore.getInstance().logInGuest(new Callback() {
public void success(Result appSessionResult) {
//Do the rest API HERE
Bundle extras = getIntent().getExtras();
String bearerToken = extras.getString("token");
try {
fetchTimelineTweet(bearerToken);
} catch (IOException e) {
e.printStackTrace();
}
}
public void failure(TwitterException e) {
Toast.makeText(getApplicationContext(), "Failure =)",
Toast.LENGTH_LONG).show();
}
});
}
And the retrieve of tweets would be:
// Fetches the first tweet from a given user's timeline
private static String fetchTimelineTweet(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + endPointUrl);
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
What i get in my log is:
380-380/com.example.john.fabric W/System.errīš• java.io.IOException: Invalid endpoint URL specified.
Is my url wrong? Or is the token which I set in the endpointURL wrong too?
Any advice would be greatly appreciated. Thanks!
That should be the case, the message was thrown by the fetchTimelineTweet function. That should be caused by this line : URL url = new URL(endPointUrl); which tells that the endPointUrl causes MalformedURLException
EDIT :
According to the Twitter Dev Page, you should put this as endpointURL : https://dev.twitter.com/rest/reference/get/statuses/user_timeline and pass the user screenname as parameter.
EDIT 2 :
I think your code should be like this :
private static String fetchTimelineTweet(String endPointUrl, String token) // this line
throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "anyApplication");
connection.setRequestProperty("Authorization", "Bearer " + token); // this line
connection.setUseCaches(false);
String res = readResponse(connection);
Log.i("Response", res);
return new String();
} catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}

Getting gibberish when sending push notification in Hebrew from java server to android phone using GCM

I am using app engine to send push notification in Hebrew to smartphone using Google Cloud Messaging, but when i receive the message on phone the text is ??????? instead of Hebrew.
Here the code for preparing Post message to phone using JSON object:
JSONObject obj=new JSONObject();
JSONArray registrationsIDList = new JSONArray();
Query newsQuery = new Query("Devices");
List<Entity> results = datastore.prepare(newsQuery).asList(
FetchOptions.Builder.withDefaults());
if(results!=null)
{
for(int j=0;j<results.size();j++)
{
Entity entity=results.get(j);
if(entity!=null)
{
String ID=(String) entity.getProperty("Registration ID");
if(ID!=null)
{
registrationsIDList.put(ID);
}
}
}
}
LinkedHashMap data = new LinkedHashMap();
data.put("Subject",subjects.get(i).getSubject());
data.put("Writer", subjects.get(i).getWriter());
data.put("SubjectDate", subjects.get(i).getLastCommentDateTime());
data.put("SubjectLink", subjects.get(i).getSubjectLink());
try {
obj.put("registration_ids", registrationsIDList);
obj.put("data", data);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Sending message to GCM for devices
try
{
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json ; charset=utf-8");
connection.setRequestProperty("Authorization", "key=*************************************");
OutputStream writer = connection.getOutputStream();
Entity tmp=new Entity("JSON");
tmp.setProperty("Message", obj.toString());
datastore.put(tmp);
writer.write(obj.toString().getBytes());
writer.close();
Entity device=new Entity("Messages Results");
device.setProperty("Response Code", connection.getResponseCode());
device.setProperty("Response Message", connection.getResponseMessage());
datastore.put(device);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException ex) {
// ...
} catch (IOException ex) {
// ...
}
Before sending the message, i checked that JSON object holds proper Hebrew text.
Here the code for receiving the message on phone:
#Override
protected void onMessage(Context arg0, Intent arg1) {
Log.d("GCM", "RECIEVED A MESSAGE");
String str = arg1.getExtras().getString("Subject");
Log.d("GCM", str);
String str1 =arg1.getExtras().getString("Writer");
Log.d("GCM", str1);
String str2 =arg1.getExtras().getString("SubjectDate");
Log.d("GCM", str2);
String str3 =arg1.getExtras().getString("SubjectLink");
Log.d("GCM", str3);
}
Now the text is ????????????????? instead of Hebrew.
Any advice will be appreciated.
You need to use Unicode: .toString.getBytes("UTF8")

How to implement C2DM in android?

I am searching about how to send notification using C2DM. I found something and using that I am able to generate Registration Key as well as an Authentication Key.
But after that in ServerSimulator class (sever side code) I got 401 Error (401 Unauthorized).Now I passed Username and Password manually, which I synchronized in my Android device. I get same error as before.
I face this problem when I click on send message button..
I am stuck on this query. Has anyone managed to do this?
public class ServerSimulator extends Activity
{
private SharedPreferences prefManager;
private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
// Registration is currently hardcoded
private final static String YOUR_REGISTRATION_STRING = "APA91bFkxmtIj5XiBU-Cze64s0gXNb7OmiWWZg-qLKibpLsVXaWq1X7hoRV9Ld9COYXirZAgkYegZBdBfUGt3lgtuhNJopvHB0KJ5ZyJ6Kt_HYRrZhgdJ1Y";
private SharedPreferences prefs;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prefManager = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem_user:
Intent intent = new Intent(this, UserPreferences.class);
startActivity(intent);
break;
default:
break;
}
return false;
}
public void getAuthentification(View view) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email","myEmail id")));
nameValuePairs.add(new BasicNameValuePair("Passwd","my password")));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source","Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
Editor edit = prefManager.edit();
edit.putString(AUTH, line.substring(5));
edit.commit();
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void showAuthentification(View view) {
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
public void sendMessage(View view) {
try {
Log.e("Tag", "Started");
String auth_key = prefManager.getString(AUTH, "n/a");
// Send a sync message to this Android device.
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(YOUR_REGISTRATION_STRING);
// if (delayWhileIdle) {
// postDataBuilder.append("&").append(PARAM_DELAY_WHILE_IDLE)
// .append("=1");
// }
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode("Lars war hier", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_key);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
Log.e("Tag", String.valueOf(responseCode));
// Validate the response code
if (responseCode == 401 || responseCode == 403) {
// The token is too old - return false to retry later, will
// fetch the token
// from DB. This happens if the password is changed or token
// expires. Either admin
// is updating the token, or Update-Client-Auth was received by
// another server,
// and next retry will get the good one from database.
Log.e("C2DM", "Unauthorized - need token");
}
// Check for updated token header
String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH);
if (updatedAuthToken != null && !auth_key.equals(updatedAuthToken)) {
Log.i("C2DM",
"Got updated auth token from datamessaging servers: "
+ updatedAuthToken);
Editor edit = prefManager.edit();
edit.putString(AUTH, updatedAuthToken);
}
String responseLine = new BufferedReader(new InputStreamReader(
conn.getInputStream())).readLine();
// NOTE: You *MUST* use exponential backoff if you receive a 503
// response code.
// Since App Engine's task queue mechanism automatically does this
// for tasks that
// return non-success error codes, this is not explicitly
// implemented here.
// If we weren't using App Engine, we'd need to manually implement
// this.
if (responseLine == null || responseLine.equals("")) {
Log.i("C2DM", "Got " + responseCode
+ " response from Google AC2DM endpoint.");
throw new IOException(
"Got empty response from Google AC2DM endpoint.");
}
String[] responseParts = responseLine.split("=", 2);
if (responseParts.length != 2) {
Log.e("C2DM", "Invalid message from google: " + responseCode
+ " " + responseLine);
throw new IOException("Invalid response from Google "
+ responseCode + " " + responseLine);
}
if (responseParts[0].equals("id")) {
Log.i("Tag", "Successfully sent data message to device: "
+ responseLine);
}
if (responseParts[0].equals("Error")) {
String err = responseParts[1];
Log.w("C2DM",
"Got error response from Google datamessaging endpoint: "
+ err);
// No retry.
throw new IOException(err);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
You are currently implementing C2DM in an older way. The way you are doing offers a lot of customizability, but not many people need that kind of customizability. With the new Google Plugin 2.4 Beta they have actually started integrating it all in, and it's pretty nice.
I'd highly recommend you watch the Google IO Android + AppEngine. They show how to integrate Android, AppEngine, and C2DM together really really simply. You can create something they call an "AppEngine Connected Android Project". So instead of making a ServerSimulator, you'd be actually working with a real server that can all be setup for free.
http://www.youtube.com/watch?v=M7SxNNC429U
If you wanted to move to another server, you'd have to re-write the server-side code, and then just change the URL that it's posting to. Pretty simple. I'd highly recommend checking out this example and working with the stock code, as it gives you something working right off the bat to play with:
FYI, there is currently a bug in the code (as it is in beta atm) when it comes to registering to a real hosted appengine server (everything works fine locally). It tries to send an expired registration token. I've been in contact with the google developers and they provided a fix for me. Let me know if you get to the point where you need it.

Categories

Resources