I am using below code to register my device for GCM
private class GetGcmRegId extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pdia = new ProgressDialog(LoginActivity.this);
pdia.setMessage("Please Wait...");
pdia.setCancelable(false);
pdia.setCanceledOnTouchOutside(false);
pdia.show();
}
#Override
protected String doInBackground(Void... params) {
GCMRegistrar.register(LoginActivity.this, Utility.SENDER_ID);
regid = GCMRegistrar.getRegistrationId(LoginActivity.this);
return regid;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdia.dismiss();
regid = result;
System.out.println("regid ==========>"+regid);
}
}
Now, one thing I know is that I will get register id via a Broadcast. But how can I make this asynctask wait until the broadcast is received?
Currently, this code System.out.println("regid ==========>"+regid);
prints nothing, but when I run the activity second time, I am receiving the register id;
In my opinion, you don't have to wait. Refer to my following sample code. Hope this helps!
Firstly, I check SharedPreferences, if empty, get token (device registration id) from Google server. Token will be stored in SharedPreferences for other use / providing to server-side app.
public class MainActivity extends Activity {
Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
SharedPreferences appPrefs = mContext.getSharedPreferences("com.example.gcmclient_preferences", Context.MODE_PRIVATE);
String token = appPrefs.getString("token", "");
if (token.isEmpty()) {
try {
getGCMToken("0123456789"); // Project ID: xxxx Project Number: 0123456789 at https://console.developers.google.com/project/...
} catch (Exception ex) {
ex.printStackTrace();
}
}
...
}
...
private void getGCMToken(final String senderId) throws Exception {
new AsyncTask<Void, Void, Void>() {
#Override
protected String doInBackground(Void... params) {
String token = "";
try {
InstanceID instanceID = InstanceID.getInstance(mContext);
token = instanceID.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
if (token != null && !token.isEmpty()) {
SharedPreferences appPrefs = mContext.getSharedPreferences("com.example.gcmclient_preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = appPrefs.edit();
prefsEditor.putString("token", token);
prefsEditor.commit();
}
Log.i("GCM_Token", token);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
}
Related
I'm trying to store my device token from my android app programmatically to AWS SNS platform application.
I'm getting an error in getApplicationContext() method. Anyone with a solution for this error?
This is my code:
public class RegisterIdForAWS extends AsyncTask<String, Void, Void> {
private Exception exception;
#Override
protected Void doInBackground(String... strings) {
try {
String pushNotificationRegId = FirebaseInstanceId.getInstance().getToken();
if (pushNotificationRegId != null) {
CognitoCachingCredentialsProvider provider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-west-2:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
Regions.US_WEST_2);
String platformApplicationArn = "arn:aws:sns:us-west-2:11111111111:app/GCM/123";
AmazonSNSClient pushClient = new AmazonSNSClient(provider);
pushClient.setRegion(Region.getRegion(Regions.US_WEST_2));
String customPushData = "";
CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
platformEndpointRequest.setCustomUserData(customPushData);
platformEndpointRequest.setToken(pushNotificationRegId);
platformEndpointRequest.setPlatformApplicationArn(platformApplicationArn);
CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(platformEndpointRequest);
Log.w(TAG, "Amazon Push reg result: " + result);
}
} catch (Exception e) {
this.exception = e;
}
return null;
}
protected void onPostExecute(String text) {
Log.w(TAG, "Amazon Push reg Finished");
}
}
In constructor of your async class, pass Context
private Context mContext;
public RegisterIdForAWS (Context context){
mContext = context;
}
And instantiate class like this:
RegisterIdForAWS task = new RegisterIdForAWS (context);
Hope it helps.
I was trying to "update" the register( for example when the user is not logged in, and then instead of a new register for the same user in a logged in mode just wanted to update the register). But didn't find an option for it, so I've decided to do it with register - unregister.
I can't seem however to unregister successfully. It just doesn't unregister.
Right now I'm trying to register and unregister right away just until I make the unregister work :
I call this at the beginning:
...
String[] args = new String[]{"000"};
args = ArrayUtils.addAll(args, "111");
args = ArrayUtils.addAll(args, "111");
register(args);
...
#SuppressWarnings("unchecked")
private void register(final String[] args) {
new AsyncTask() {
#Override
protected Object doInBackground(Object... params) {
try {
String regid = gcm.register(SENDER_ID);
String regRes = hub.register(regid, args).getRegistrationId();
} catch (Exception e) {
e.printStackTrace();
return e;
}
return null;
}
#Override
protected void onPostExecute(Object result) {
unregister1();
};
}.execute(null, null, null);
}
public void unregister1()
{
new AsyncTask() {
#Override
protected Object doInBackground(Object... params) {
try
{
//gcm.unregister();
hub.unregister();
}
catch (Exception e)
{
Log.d("TAG","error");
e.printStackTrace();
}
return null;
}
};
}
I have this AsyncTask:
public static void login(final String email, final String password,
final String token, final SocketHandler handler) {
execute(new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(final Void... params) {
Log.d("ACEPTAR", "DOINBACKGROUND");
String url = handler.servidor.getUrl();
url += "/login-usuario";
String str;
try {
str = postResponseFromServer(url, "mail", email, "pass",
password, "tipo", "1", "token", token);
Log.d("ACEPTAR", str);
final CustomJSONObject object = new CustomJSONObject(str);
final CustomJSONObject object2 = new CustomJSONObject();
object2.put("datos", object);
final CustomJSONArray array = new CustomJSONArray();
array.put(object2);
handler.on("resultado-login", array);
} catch (final Exception ex) {
ex.printStackTrace();
handler.on("error-login", new CustomJSONArray());
}
return null;
}
});
}
#SuppressLint("InlinedApi")
private static void execute(final AsyncTask<Void, Void, Void> task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
} else {
task.execute();
}
}
I try to do it on 3G, always works. Then I connect to Wi-Fi. The AsyncTask gets called on 4.0+, but not in 2.3.7-.
Am I missing something?
Try creating a separate Thread and do your stuff in there, post your results with Activity.runInUiThread(). See if there's any problem with that. If there's no problem, then it's perhaps because of some AsyncTask bug.
Is there a way to get the token that was used to log in the user with Google Play Game Services?
I'm looking for something like:
#Override
public void onSignInSucceeded() {
String email = getGamesClient().getCurrentAccountName();
String token = getGamesClient().getToken();
}
I need this to authenticate the user when they are contacting my own server.
This is how I managed to get the token:
#Override
public void onSignInSucceeded() {
String email = getGamesClient().getCurrentAccountName();
String scopes = getScopes();
new registerBackground(getApplicationContext()).execute(email, scopes);
}
private class registerBackground extends AsyncTask<String, Void, Void> {
Context context;
registerBackground (Context context) {
this.context = context;
}
#Override
protected Void doInBackground(String... params) {
try {
String oAuthToken = GoogleAuthUtil.getToken(context, params[0], params[1]);
...
catch (Exception e) {
e.printStackTrace();
}
}
...
}
i am trying to access saved preferences from within an asynctask but i always keep getting the error "preferences can not be resolved". Any ideas? Here is a part of the code:
public class Login extends SherlockActivity {
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
new LongOperationLogin(this).execute();
}
}
class LongOperationLogin extends AsyncTask<String, Void, String> {
private Login longOperationContext = null;
public LongOperationLogin(Login context) {
longOperationContext = context;
}
#Override
protected String doInBackground(String... params) {
//THIS IS WHERE I NEED THE VALUE
String username = this.preferences.getString("username", "n/a");
try {
//JSON fetching
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.v("Error", "URL exc");
} catch (IOException e) {
e.printStackTrace();
Log.v("ERROR", "IOEXECPTOIn");
} catch (JSONException e) {
e.printStackTrace();
Log.v("Error", "JsonException");
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
protected void onPreExecute() {
}
protected void onProgressUpdate(Void... values) {
}
}
Thanks in advance!
Robert
You should access your preferece variable with Login.this.preferences. Also make sure that your AsyncTask is an inner class (contained in Login).
Try this
String username = longOperationContext.preferences.getString("username", "n/a");
and make preferences field public