RegisterIntentService.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Feel free to copy/use it for your own project.
  3. * Keep in mind that it took me several days/weeks, beers and asperines to make this.
  4. * So be nice, and give me some credit, I won't bite and it won't hurt you.
  5. *
  6. * Created by Deben Oldert
  7. */
  8. package com.dev.deben.implementation;
  9. import android.app.IntentService;
  10. import android.content.Intent;
  11. import com.google.android.gms.gcm.GoogleCloudMessaging;
  12. import com.google.android.gms.iid.InstanceID;
  13. import org.json.JSONException;
  14. import java.io.IOException;
  15. import java.util.HashMap;
  16. public class RegisterIntentService extends IntentService {
  17. private static final String TAG = "RegIntentService";
  18. public RegisterIntentService() {
  19. super(TAG);
  20. }
  21. function fn = new function(this);
  22. @Override
  23. protected void onHandleIntent(Intent intent) {
  24. try {
  25. InstanceID instanceID = InstanceID.getInstance(this);
  26. String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
  27. GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
  28. System.out.println("Service creating token");
  29. System.out.println("Token: "+token);
  30. sendRegistrationToServer(token);
  31. } catch (Exception e) {
  32. System.out.println("Failed to complete token refresh");
  33. }
  34. }
  35. private void sendRegistrationToServer(String token) throws IOException, JSONException {
  36. System.out.println("REGISTERING TOKEN");
  37. HashMap<String, String> set = new HashMap<>();
  38. set.put("notificationId", token);
  39. fn.writeSetting(set);
  40. }
  41. }