private void GetDeviceToken(Context context) { // Load token from settings var settings = context.GetSharedPreferences("AerogearPushConfig", FileCreationMode.Private); var token = settings.GetString(TOKEN_KEY, String.Empty); // If the token obtained from seetings is empty, send a new token request to GCM if (String.IsNullOrWhiteSpace(token)) { var gcm = GoogleCloudMessaging.GetInstance(context); try { token = gcm.Register(GCM_SENDER_ID); } catch (Exception e) { // TODO An exception might be rarely thrown here, if the // GCM service is not responding. Handle this case here. } // Store the token in SharedPreferences var editor = settings.Edit(); editor.PutString(TOKEN_KEY, token); //@ todo in AeroGearGCMPushRegistrar:302 the appversion is also saved? //@ todo Set expiration time editor.Commit(); } DeviceToken = token; // check if app was updated; if so, it must clear registration id to // avoid a race condition if a GCM sends a message // @TODO TBD. See AeroGearGCMPushRegistrar.java:246 }
private async void RegisterDevice() { var regId = RegistrationId; if (regId == null) { // Obtain registration id for app: var ctx = ServiceContainer.Resolve <Context> (); var gcm = GoogleCloudMessaging.GetInstance(ctx); try { RegistrationId = regId = await System.Threading.Tasks.Task.Factory.StartNew(() => gcm.Register(Build.GcmSenderId)); } catch (Exception exc) { var log = ServiceContainer.Resolve <ILogger> (); log.Info(Tag, exc, "Failed register device for GCM push."); return; } } // Register user device with server var pushClient = ServiceContainer.Resolve <IPushClient> (); IgnoreTaskErrors(pushClient.Register(authToken, PushService.GCM, regId)); }
protected override void OnHandleIntent(Intent intent) { var extras = intent.Extras; var gcm = GoogleCloudMessaging.GetInstance(this); // intent must be the one received in GcmBroadcastReceiver var messageType = gcm.GetMessageType(intent); if (!extras.IsEmpty) { var notificationBroadcast = new Intent(Constants.IntentFilter); notificationBroadcast.PutExtra("notificationType", messageType); try { // lets be a bit naive here. If this crashes, fix your JSON! // However, proper services like Azure NotificationHub // validates the payload before pushing it :) var json = new JObject(); foreach (var key in extras.KeySet()) { var content = extras.Get(key); if (content.ToString().StartsWith("{")) { // lets assume this is a JSON object var obj = JObject.Parse(content.ToString()); json.Add(new JProperty(key, obj)); } else if (content.ToString().StartsWith("[")) { // lets assume this is a JSON array var array = JArray.Parse(content.ToString()); json.Add(new JProperty(key, array)); } else { var property = new JProperty(key, content.ToString()); json.Add(property); } } Log.Debug("GcmBroadcastReceiver", "json: {0}", json.ToString()); notificationBroadcast.PutExtra("notificationJson", json.ToString()); } catch (Exception e) { var json = new JObject(new JProperty("error", e.Message)); notificationBroadcast.PutExtra("notificationJson", json.ToString()); } SendBroadcast(notificationBroadcast); } // Release wake lock from the GcmBroadcastReceiver GcmBroadcastReceiver.CompleteWakefulIntent(intent); }
private async Task InternalRegister() { Context context = Android.App.Application.Context; System.Diagnostics.Debug.WriteLine(string.Format("{0} - Registering push notifications", PushNotificationKey.DomainName)); if (CrossPushNotification.SenderId == null) { throw new ArgumentException("No Sender Id Specified"); } try { GoogleCloudMessaging gcm = GoogleCloudMessaging.GetInstance(context); string regId = await Task.Run(() => { return(gcm.Register(CrossPushNotification.SenderId)); }); System.Diagnostics.Debug.WriteLine(string.Format("{0} - Device registered, registration ID=" + regId, PushNotificationKey.DomainName)); if (CrossPushNotification.IsInitialized) { CrossPushNotification.PushNotificationListener.OnRegistered(regId, DeviceType.Android); } else { throw NewPushNotificationNotInitializedException(); } // Persist the regID - no need to register again. StoreRegistrationId(context, regId); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("{0} - Error :" + ex.Message, PushNotificationKey.DomainName)); if (CrossPushNotification.IsInitialized) { CrossPushNotification.PushNotificationListener.OnError(string.Format("{0} - Register - " + ex.ToString(), PushNotificationKey.DomainName), DeviceType.Android); } else { throw NewPushNotificationNotInitializedException(); } } }
protected override void OnHandleIntent(Intent intent) { var extras = intent.Extras; var gcm = GoogleCloudMessaging.GetInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. var messageType = gcm.GetMessageType(intent); if (!extras.IsEmpty) // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ { if (GoogleCloudMessaging.MessageTypeSendError.Equals(messageType)) { SendNotification("Send error: " + extras); } else if (GoogleCloudMessaging.MessageTypeDeleted.Equals(messageType)) { SendNotification("Deleted messages on server: " + extras); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MessageTypeMessage.Equals(messageType)) { // This loop represents the service doing some work. for (int i = 0; i < 5; i++) { Console.Write(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.ElapsedRealtime()); try { Thread.Sleep(5000); } catch (Java.Lang.InterruptedException) { } } Console.Write(TAG, "Completed work @ " + SystemClock.ElapsedRealtime()); // Post notification of received message. SendNotification("Received: " + extras); Console.Write(TAG, "Received: " + extras); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GCMBroadcastReceiver.CompleteWakefulIntent(intent); }
bool SendUpstreamMessage(string msg) { var gcm = GoogleCloudMessaging.GetInstance(this); try { var data = new Bundle(); data.PutString("my_message", msg); var id = msgId++; gcm.Send(MyRegistrationService.GCM_SENDER_ID + "@gcm.googleapis.com", id.ToString(), data); return(true); } catch (Exception ex) { Android.Util.Log.Error(TAG, "SendUpstreamMessage Failed: {0}", ex); } return(false); }
/** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void RegisterInBackground() { Thread _Thread = new Thread(() => { try { if (gcm == null) { gcm = GoogleCloudMessaging.GetInstance(ApplicationContext); } regid = gcm.Register(SENDER_ID); SendRegistrationIdToBackend(); StoreRegistrationId(ApplicationContext, regid); } catch (Java.IO.IOException ex) { Log.Info(TAG, ex.Message); } //return msg; }); _Thread.Start(); }
public override void OnReceive(Context context, Intent intent) { GoogleCloudMessaging gcm = GoogleCloudMessaging.GetInstance(context); String messageType = gcm.GetMessageType(intent); if (GoogleCloudMessaging.MessageTypeSendError.Equals(messageType)) { PushReceiver.Instance.OnMessageError(); } else if (GoogleCloudMessaging.MessageTypeDeleted.Equals(messageType)) { var message = intent.Extras.GetString("alert"); PushReceiver.Instance.OnMessageDelete(message); } else { var message = intent.Extras.GetString("alert"); PushReceiver.Instance.OnMessageReceived(message); } }
void RegisterInBackground() { Task.Factory.StartNew(() => { Console.WriteLine("Starting Background Thread"); try { if (GCM == null) { GCM = GoogleCloudMessaging.GetInstance(ApplicationContext); } RegID = GCM.Register(SenderID); Console.WriteLine("From Background task: " + RegID); storage.Put(PropertyRegID, RegID); // TODO You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. // sendRegistrationIdToBackend(); } catch (Java.IO.IOException) { storage.Put("failed_registration", true); } }).ContinueWith(task => RunOnUiThread(() => Toast.MakeText(this, "Background Task Finished", ToastLength.Long))); }
private async Task InternalUnRegister() { System.Diagnostics.Debug.WriteLine(string.Format("{0} - Unregistering push notifications", PushNotificationKey.DomainName)); GoogleCloudMessaging gcm = GoogleCloudMessaging.GetInstance(Android.App.Application.Context); await Task.Run(() => { gcm.Unregister(); }); if (CrossPushNotification.IsInitialized) { CrossPushNotification.PushNotificationListener.OnUnregistered(DeviceType.Android); } else { throw NewPushNotificationNotInitializedException(); } StoreRegistrationId(Android.App.Application.Context, string.Empty); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); RequestWindowFeature(WindowFeatures.IndeterminateProgress); SetContentView(Resource.Layout.Navigation); if (HasPlayServices) { GCM = GoogleCloudMessaging.GetInstance(this); RegID = RegistrationId; if (String.IsNullOrEmpty(RegID)) { RegisterInBackground(); } else { Console.WriteLine("Seems like we have a RegID"); } } cnHelper = ConnectivityHelper.Instance(this); mDrawerLayout = FindViewById <DrawerLayout> (Resource.Id.drawer_layout); mDrawerList = FindViewById <ListView> (Resource.Id.left_drawer); mDrawerList.Adapter = new DrawerAdapter(this); mDrawerList.ItemClick += (sender, e) => { switch (e.Position) { case 0: var publications = new PublicationsFragment(false); FragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, publications).Commit(); SetTitle(Resource.String.main_title); mDrawerLayout.CloseDrawer(mDrawerList); break; case 1: var companies = new CompaniesFragment(); FragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, companies).Commit(); SetTitle(Resource.String.companies); mDrawerLayout.CloseDrawer(mDrawerList); break; } }; mDrawerLayout.SetDrawerShadow(Resource.Drawable.drawer_shadow, GravityCompat.Start); ActionBar.SetDisplayHomeAsUpEnabled(true); ActionBar.SetHomeButtonEnabled(true); DrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, Resource.Drawable.ic_navigation_drawer, Resource.String.drawer_open, Resource.String.drawer_close); mDrawerLayout.SetDrawerListener(DrawerToggle); mDrawerLayout.DrawerOpened += delegate { ActionBar.SetTitle(Resource.String.menu); //mDrawerLayout. InvalidateOptionsMenu(); }; mDrawerLayout.DrawerClosed += delegate { SetTitle(mTitle); InvalidateOptionsMenu(); }; pubs = new PublicationsFragment(); FragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, pubs).Commit(); mDrawerList.SetItemChecked(0, true); HandleIntent(Intent); }
private void Initialize() { //Xamarin.Insights.Initialize(global::InPublishing.XamarinInsights.ApiKey, this); AppCenter.Start("cab73ad7-da5e-4ce1-a472-6d48df685f2f", typeof(Analytics), typeof(Crashes)); //image loader var config = new ImageLoaderConfiguration.Builder(ApplicationContext); config.ThreadPriority(Java.Lang.Thread.NormPriority - 2); config.DenyCacheImageMultipleSizesInMemory(); config.DiskCacheFileNameGenerator(new Md5FileNameGenerator()); config.DiskCacheSize(50 * 1024 * 1024); // 50 MiB config.TasksProcessingOrder(QueueProcessingType.Lifo); config.WriteDebugLogs(); // Remove for release app // Initialize ImageLoader with configuration. ImageLoader.Instance.Init(config.Build()); if (!DataManager.AlreadyRegistered <ISettingsManager>()) { DataManager.RegisterReference <ISettingsManager, SettingsManager>(); } DataManager.Get <ISettingsManager>().AndroidGetSettings = p => { string content; using (StreamReader sr = new StreamReader(Assets.Open("AppSettings.xml"))) { content = sr.ReadToEnd(); return(content); } }; DataManager.Get <ISettingsManager>().Load(); //se è attiva la condivisione setto la cartella nella root string sharedPath = ""; if (DataManager.Get <ISettingsManager>().Settings.ShareDir) { string appName = ApplicationInfo.LoadLabel(PackageManager); sharedPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, appName); } else { sharedPath = GetExternalFilesDir("shared").AbsolutePath; } if (this.CanAccessExternal()) { if (!Directory.Exists(sharedPath)) { Directory.CreateDirectory(sharedPath); } } //cartella per le pubblicazioni nascosta /*#if DEBUG * string docPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.Inpublishing/Publications"; * string notePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.Inpublishing/Notes";*/ //#else string docPath = GetExternalFilesDir("publications").AbsolutePath; string notePath = GetExternalFilesDir("notes").AbsolutePath; //#endif //Se non esiste la creo if (!Directory.Exists(docPath)) { Directory.CreateDirectory(docPath); } DataManager.Get <ISettingsManager>().Settings.Debug = true; DataManager.Get <ISettingsManager>().Settings.DocPath = docPath; DataManager.Get <ISettingsManager>().Settings.SharedPath = sharedPath; DataManager.Get <ISettingsManager>().Settings.NotePath = notePath; DataManager.Get <ISettingsManager>().Settings.AndroidContext = this; /*WifiManager manager = Application.Context.GetSystemService (Context.WifiService) as WifiManager; * WifiInfo info = manager.ConnectionInfo; * string address = info.MacAddress;*///uuid ISharedPreferences prefs = GetSharedPreferences(this.PackageName, FileCreationMode.Private); string deviceId = prefs.GetString("UniqueDeviceIdentifier", ""); if (deviceId == "") { //Guid guid = Guid.NewGuid(); //deviceId = guid.ToString (); deviceId = Android.Provider.Settings.Secure.GetString(ApplicationContext.ContentResolver, Android.Provider.Settings.Secure.AndroidId); ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("UniqueDeviceIdentifier", deviceId); editor.Apply(); } DataManager.Get <ISettingsManager>().Settings.DeviceUID = deviceId; DataManager.Get <ISettingsManager>().Settings.DeviceOS = DocumentOS.Android; DataManager.Get <ISettingsManager>().Settings.DeviceType = Utility.IsTablet(this) ? DocumentDevice.Tablet : DocumentDevice.Phone; //statistiche DataManager.Get <ISettingsManager>().Settings.StatsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); FileSystemManager.AndroidCopyFunc = delegate() { //se è singola e devo importare i documenti elimino quelli presenti if (DataManager.Get <ISettingsManager>().Settings.SingolaApp&& Directory.Exists(DataManager.Get <ISettingsManager>().Settings.DocPath)) { System.IO.DirectoryInfo di = new DirectoryInfo(DataManager.Get <ISettingsManager>().Settings.DocPath); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } } string dPath = DataManager.Get <ISettingsManager>().Settings.SharedPath; AssetManager am = Resources.Assets; var files = am.List("pub"); foreach (string file in files) { using (Stream source = Assets.Open("pub/" + file)) { if (!File.Exists(Path.Combine(dPath, file))) { using (var dest = System.IO.File.Create(Path.Combine(dPath, file))) { source.CopyTo(dest); } } } } }; FileSystemManager.AndroidCountFunc = p => { AssetManager am = Resources.Assets; return(am.List("pub").Length); }; //preferenze if (!DataManager.AlreadyRegistered <IPreferencesManager>()) { DataManager.RegisterReference <IPreferencesManager, PreferencesManager>(); } DataManager.Get <ISettingsManager>().Load(); //ordinamento if (!DataManager.Get <IPreferencesManager>().Preferences.AlreadyRun) { var order = DataManager.Get <ISettingsManager>().Settings.EdicolaOrder; DataManager.Get <IPreferencesManager>().Preferences.EdicolaOrder = order; DataManager.Get <IPreferencesManager>().Save(); } //notifiche if (CheckPlayServices()) { gcm = GoogleCloudMessaging.GetInstance(this); regid = GetRegistrationId(ApplicationContext); //regid = ""; if (regid == "") { //ConnectivityManager connectivityManager = (ConnectivityManager) GetSystemService(ConnectivityService); NetworkStatus internetStatus = Reachability.InternetConnectionStatus(); if (internetStatus == NetworkStatus.ReachableViaCarrierDataNetwork || internetStatus == NetworkStatus.ReachableViaWiFiNetwork) { RegisterInBackground(); } } else //anche se ho già il token registro comunque il dispositivo sull'edicola, saltando la richiesta del token però { Thread _Thread = new Thread(() => { try { SendRegistrationIdToBackend(); } catch (Java.IO.IOException ex) { Log.Info(TAG, ex.Message); } }); _Thread.Start(); } } else { Log.Info(TAG, "No valid Google Play Services APK found."); } //se la versione è diversa setto come se fosse la prima volta che l'app parte string version = PackageManager.GetPackageInfo(PackageName, 0).VersionCode.ToString(); if (DataManager.Get <IPreferencesManager>().Preferences.AppVersion == "" || DataManager.Get <IPreferencesManager>().Preferences.AppVersion != version) { DataManager.Get <IPreferencesManager>().Preferences.DocImported = false; } DataManager.Get <IPreferencesManager>().Preferences.AppVersion = version; DataManager.Get <IPreferencesManager>().Save(); if (DataManager.Get <ISettingsManager>().Settings.EdicolaEnabled&& !DataManager.Get <ISettingsManager>().Settings.SingolaApp) { //var intent = new Intent(this, typeof(EdicolaScreen)); var intent = new Intent(this, typeof(HomeScreen)); intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop); StartActivity(intent); } else { var intent = new Intent(this, typeof(DownloaderScreen)); intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop); StartActivity(intent); } StatisticheManager.SendStats(); MBDownloadManager.RemoveAll(); //google analytics AnalyticsService.Initialize(this); AnalyticsService.SendEvent("App", AnalyticsEventAction.AppStart); DataManager.Get <IPreferencesManager>().Preferences.AlreadyRun = true; DataManager.Get <IPreferencesManager>().Save(); }