private void AddReceiver() { var filter = new IntentFilter(); filter.AddAction(IntentFilterName); Receiver = new KillBroadcastReceiver { OnReceiveAction = () => RunOnUiThread(Finish) }; RegisterReceiver(Receiver, filter); }
private void RegisterBroadcastReceiver() { IntentFilter filter = new IntentFilter(GPSServiceReciever.LOCATION_UPDATED); filter.AddCategory(Intent.CategoryDefault); _receiver = new GPSServiceReciever(); RegisterReceiver(_receiver, filter); }
public static void Initialize(Context ctx) { P2PManager.ctx = ctx; if (intentFilter == null) { intentFilter = new IntentFilter(); intentFilter.AddAction(WifiP2pManager.WifiP2pStateChangedAction); intentFilter.AddAction(WifiP2pManager.WifiP2pPeersChangedAction); intentFilter.AddAction(WifiP2pManager.WifiP2pConnectionChangedAction); intentFilter.AddAction(WifiP2pManager.WifiP2pThisDeviceChangedAction); } if (manager == null) { manager = (WifiP2pManager)ctx.GetSystemService(Context.WifiP2pService); channel = manager.Initialize(ctx, ctx.MainLooper, null); } if (receiver == null) { receiver = new WiFiDirectBroadcastReceiver(manager, channel); } ctx.RegisterReceiver(receiver, intentFilter); }
protected override void OnResume() { base.OnResume(); // Setup the receivers for the service's results IntentFilter initIntentFilter = new IntentFilter(ServiceAction.INIT.ToString()); initActivityReceiver = new InitActivityReceiver(); // Registers the receiver and its intent filters RegisterReceiver(initActivityReceiver, initIntentFilter); // Setup the connection receiver IntentFilter connectIntentFilter = new IntentFilter(ServiceAction.CONNECT.ToString()); connectActivityReceiver = new ConnectActivityReceiver(); // Registers the receiver and its intent filters RegisterReceiver(connectActivityReceiver, connectIntentFilter); // Setup the message sent receiver IntentFilter messageIntentFilter = new IntentFilter(ServiceAction.SENDMESSAGE.ToString()); messageActivityReceiver = new MesssageActivityReceiver(); // Registers the receiver and its intent filters RegisterReceiver(messageActivityReceiver, messageIntentFilter); // Starts the IntentService and connects Intent mServiceIntent = new Intent(this, typeof(BackgroundService)); mServiceIntent.PutExtra(ServiceMessage.JID, jid); mServiceIntent.PutExtra(ServiceMessage.PASSWORD, password); mServiceIntent.SetAction(ServiceAction.INIT.ToString()); StartService(mServiceIntent); Utils.SetConnectionAlarm(this); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(R.Layout.local_service_broadcaster); // This is where we print the data we get back. TextView callbackData = (TextView)FindViewById(R.Id.callback); // Put in some initial text. callbackData.Text = ("No broadcast received yet"); // We use this to send broadcasts within our local process. mLocalBroadcastManager = LocalBroadcastManager.GetInstance(this); // We are going to watch for interesting local broadcasts. IntentFilter filter = new IntentFilter(); filter.AddAction(ACTION_STARTED); filter.AddAction(ACTION_UPDATE); filter.AddAction(ACTION_STOPPED); mReceiver = new MyBroadcastReceiver(callbackData); mLocalBroadcastManager.RegisterReceiver(mReceiver, filter); // Watch for button clicks. Button button = (Button)FindViewById(R.Id.start); button.Click += (o,e) => StartService(new Intent(this, typeof(LocalService))); button = (Button)FindViewById(R.Id.stop); button.Click += (o,e) => StopService(new Intent(this, typeof(LocalService))); }
protected override void OnCreate(Bundle bundle) { var intentFilter = new IntentFilter(); intentFilter.AddAction(ConnectivityManager.ConnectivityAction); RegisterReceiver(new Connectivity(), intentFilter); base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); connectivity.Singleton.MessageEvents.Change += (object s, UIChangedEventArgs ea) => { if (ea.ModuleName == "Notification") { RunOnUiThread(() => { var builder = new Notification.Builder(this) .SetAutoCancel(true) .SetContentTitle("Network state changed") .SetContentText(ea.Info) .SetDefaults(NotificationDefaults.Vibrate) .SetContentText(ea.Info); var notificationManager = (NotificationManager)GetSystemService(NotificationService); notificationManager.Notify(ButtonClickNotificationId, builder.Build()); }); } }; LoadApplication(new App()); }
public override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); ContentView = R.layout.activity_nv_image; mImageView = (ImageView) findViewById(R.id.imageView1); mTextView = (TextView) findViewById(R.id.textView3); Button button = (Button) findViewById(R.id.button1); button.OnClickListener = this; button = (Button) findViewById(R.id.button2); button.OnClickListener = this; button = (Button) findViewById(R.id.button3); button.OnClickListener = this; button = (Button) findViewById(R.id.button4); button.OnClickListener = this; button = (Button) findViewById(R.id.button5); button.OnClickListener = this; mAdapter = new ArrayAdapter<string>(this, android.R.layout.simple_list_item_single_choice, mArrayList); mListView = (ListView) findViewById(R.id.listView1); mListView.Adapter = mAdapter; mListView.ChoiceMode = ListView.CHOICE_MODE_SINGLE; IntentFilter filter = new IntentFilter(); filter.addAction(MainActivity.ACTION_GET_DEFINEED_NV_IMAGE_KEY_CODES); registerReceiver(mReceiver, filter); MainActivity.mBixolonPrinter.DefinedNvImageKeyCodes; }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Setup the window RequestWindowFeature (WindowFeatures.IndeterminateProgress); SetContentView (Resource.Layout.device_list); // Set result CANCELED incase the user backs out SetResult (Result.Canceled); // Initialize the button to perform device discovery var scanButton = FindViewById<Button> (Resource.Id.button_scan); scanButton.Click += (sender, e) => { DoDiscovery (); (sender as View).Visibility = ViewStates.Gone; }; // Initialize array adapters. One for already paired devices and // one for newly discovered devices pairedDevicesArrayAdapter = new ArrayAdapter<string> (this, Resource.Layout.device_name); newDevicesArrayAdapter = new ArrayAdapter<string> (this, Resource.Layout.device_name); // Find and set up the ListView for paired devices var pairedListView = FindViewById<ListView> (Resource.Id.paired_devices); pairedListView.Adapter = pairedDevicesArrayAdapter; pairedListView.ItemClick += DeviceListClick; // Find and set up the ListView for newly discovered devices var newDevicesListView = FindViewById<ListView> (Resource.Id.new_devices); newDevicesListView.Adapter = newDevicesArrayAdapter; newDevicesListView.ItemClick += DeviceListClick; // Register for broadcasts when a device is discovered receiver = new Receiver (this); var filter = new IntentFilter (BluetoothDevice.ActionFound); RegisterReceiver (receiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter (BluetoothAdapter.ActionDiscoveryFinished); RegisterReceiver (receiver, filter); // Get the local Bluetooth adapter btAdapter = BluetoothAdapter.DefaultAdapter; // Get a set of currently paired devices var pairedDevices = btAdapter.BondedDevices; // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.Count > 0) { FindViewById<View> (Resource.Id.title_paired_devices).Visibility = ViewStates.Visible; foreach (var device in pairedDevices) { pairedDevicesArrayAdapter.Add (device.Name + "\n" + device.Address); } } else { String noDevices = Resources.GetText (Resource.String.none_paired); pairedDevicesArrayAdapter.Add (noDevices); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.main); locationButton = (Button)FindViewById(Resource.Id.location_button); locationButton.Click += delegate { StartActivity(new Intent(BaseContext, typeof (LocationActivity))); }; // Set up custom preference screen style button Button customPreferencesButton = (Button)FindViewById(Resource.Id.push_custom_preferences_button); customPreferencesButton.Click += delegate { StartActivity(new Intent(BaseContext, typeof (CustomPreferencesActivity))); }; // Set up android built-in preference screen style button Button preferencesButton = (Button)FindViewById(Resource.Id.push_preferences_button); preferencesButton.Click += delegate { StartActivity(new Intent(BaseContext, typeof (PreferencesActivity))); }; boundServiceFilter = new IntentFilter(); boundServiceFilter.AddAction(UALocationManager.GetLocationIntentAction(UALocationManager.ActionSuffixLocationServiceBound)); boundServiceFilter.AddAction(UALocationManager.GetLocationIntentAction(UALocationManager.ActionSuffixLocationServiceUnbound)); apidUpdateFilter = new IntentFilter(); apidUpdateFilter.AddAction(UAirship.PackageName + IntentReceiver.APID_UPDATED_ACTION_SUFFIX); }
private void registerBroadcastReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(SpassFingerprint.ACTION_FINGERPRINT_RESET); filter.addAction(SpassFingerprint.ACTION_FINGERPRINT_REMOVED); filter.addAction(SpassFingerprint.ACTION_FINGERPRINT_ADDED); mContext.registerReceiver(mPassReceiver, filter); };
public override void OnCreate() { base.OnCreate(); nlservicereceiver = new NLSServiceReceiver(); IntentFilter filter = new IntentFilter(); filter.AddAction("com.dpwebdev.handsetfree.NOTIFICATION_LISTENER_SERVICE_EXAMPLE"); RegisterReceiver(nlservicereceiver, filter); }
/// <summary> /// register to service /// </summary> private void RegisterBroadcastReceiver() { IntentFilter filter = new IntentFilter(MsgBroadcasrReceiver.MSG_BCAST); filter.AddCategory(Intent.CategoryDefault); _receiver = new MsgBroadcasrReceiver(); RegisterReceiver(_receiver, filter); }
public override void OnCreate() { base.OnCreate(); _screenOffReceiver = new ScreenOffReceiver(); IntentFilter filter = new IntentFilter(); filter.AddAction(Intent.ActionScreenOff); RegisterReceiver(_screenOffReceiver, filter); }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); Console.WriteLine ("XamFace: OnCreate Called"); displayManager = (DisplayManager)GetSystemService (Context.DisplayService); displayManager.RegisterDisplayListener (this, null); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); time = FindViewById<TextView> (Resource.Id.textTime); date = FindViewById<TextView> (Resource.Id.textDate); day = FindViewById<TextView> (Resource.Id.textDay); xamarinLogo = FindViewById<ImageView> (Resource.Id.xamarinLogo); wheelSeconds = FindViewById<ProgressWheel> (Resource.Id.wheelSeconds); wheelMinutes = FindViewById<ProgressWheel> (Resource.Id.wheelMinutes); wheelHours = FindViewById<ProgressWheel> (Resource.Id.wheelHours); wheelMinutes.Alpha = 0.6f; wheelHours.Alpha = 0.3f; wheelHours.ProgressMax = 24; wheelSeconds.RimColor = Android.Graphics.Color.Transparent; wheelHours.RimColor = Android.Graphics.Color.Transparent; wheelMinutes.RimColor = Android.Graphics.Color.Transparent; RunOnUiThread (UpdateUI); var filter = new IntentFilter (); filter.AddAction (Intent.ActionTimeTick); filter.AddAction (Intent.ActionTimeChanged); filter.AddAction (Intent.ActionTimezoneChanged); timeBroadcastReceiver = new SimpleBroadcastReceiver (); timeBroadcastReceiver.Receive = () => { Console.WriteLine ("Time Changed"); RunOnUiThread (UpdateUI); }; RegisterReceiver (timeBroadcastReceiver, filter); batteryBroadcastReceiver = new SimpleBroadcastReceiver (); batteryBroadcastReceiver.Receive = () => { Console.WriteLine ("Battery Changed"); RunOnUiThread (UpdateUI); }; RegisterReceiver (batteryBroadcastReceiver, new IntentFilter (Intent.ActionBatteryChanged)); timerSeconds = new Timer (new TimerCallback (state => { RunOnUiThread (() => UpdateUITime (null)); }), null, TimeSpan.FromSeconds (1), TimeSpan.FromSeconds (1)); }
public DroidBatteryService() { IntentFilter ifilter = new IntentFilter(Intent.ActionBatteryChanged); _batteryStatus = Application.Context.RegisterReceiver(this, ifilter); isCharging = null; usbCharge = null; acCharge = null; batteryLevel = null; }
public void batteryStatus() { var filter = new IntentFilter(Intent.ActionBatteryChanged); var battery = RegisterReceiver(null, filter); int level = battery.GetIntExtra(BatteryManager.ExtraLevel, -1); int scale = battery.GetIntExtra(BatteryManager.ExtraScale, -1); int BPercetage = (int)System.Math.Floor(level * 100D / scale); batteryStatusTextView.Text += BPercetage + "%"; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); _ioc = App.Kp2a.GetDb().Ioc; _intentReceiver = new LockingClosePreferenceActivityBroadcastReceiver(this); IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.DatabaseLocked); RegisterReceiver(_intentReceiver, filter); }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.main); var refreshbattery = FindViewById<Button> (Resource.Id.refresh_battery); var batterystatus = FindViewById<TextView> (Resource.Id.battery_status); var batterylevel = FindViewById<TextView> (Resource.Id.battery_level); refreshbattery.Click += (sender, e) => { var filter = new IntentFilter(Intent.ActionBatteryChanged); var battery = RegisterReceiver(null, filter); int level = battery.GetIntExtra(BatteryManager.ExtraLevel, -1); int scale = battery.GetIntExtra(BatteryManager.ExtraScale, -1); batterylevel.Text = string.Format("Current Charge: {0}%", Math.Floor (level * 100D / scale)); // Are we charging / charged? works on phones, not emulators must check how. int status = battery.GetIntExtra(BatteryManager.ExtraStatus, -1); var isCharging = status == (int)BatteryStatus.Charging || status == (int)BatteryStatus.Full; // How are we charging? var chargePlug = battery.GetIntExtra(BatteryManager.ExtraPlugged, -1); var usbCharge = chargePlug == (int)BatteryPlugged.Usb; var acCharge = chargePlug == (int)BatteryPlugged.Ac; var wirelessCharge = chargePlug == (int)BatteryPlugged.Wireless; isCharging = (usbCharge || acCharge || wirelessCharge); if(!isCharging){ batterystatus.Text = "Status: discharging"; } else if(usbCharge){ batterystatus.Text = "Status: charging via usb"; } else if(acCharge){ batterystatus.Text = "Status: charging via ac"; } else if(wirelessCharge){ batterystatus.Text = "Status: charging via wireless"; } }; recyclerView = FindViewById<RecyclerView> (Resource.Id.recycler_view); recyclerView.HasFixedSize = true; layoutManager = new LinearLayoutManager (this); recyclerView.SetLayoutManager (layoutManager); var items = new List<RecyclerItem> (100); for(int i = 0; i < 100; i++) items.Add(new RecyclerItem{Title = "Item: " + i}); adapter = new RecyclerAdapter (items); recyclerView.SetAdapter (adapter); }
public override void OnResume() { base.OnResume(); var filter = new IntentFilter(); filter.AddAction(TileEvent.ActionTileOpened); filter.AddAction(TileEvent.ActionTileButtonPressed); filter.AddAction(TileEvent.ActionTileClosed); Application.Context.RegisterReceiver(tileReceiver, filter); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.receiver_demo); _receiver = new BatteryReceiver(); var intentFilter = new IntentFilter(Intent.ActionPowerConnected); intentFilter.AddAction(Intent.ActionPowerDisconnected); RegisterReceiver(_receiver, intentFilter); }
protected override void OnStart () { base.OnStart (); var intentFilter = new IntentFilter (StockService.StocksUpdatedAction){Priority = (int)IntentFilterPriority.HighPriority}; RegisterReceiver (stockReceiver, intentFilter); stockServiceConnection = new StockServiceConnection (this); BindService (stockServiceIntent, stockServiceConnection, Bind.AutoCreate); ScheduleStockUpdates (); }
private void AddJob(AppTask task) { if (_Jobs == null) { _Jobs = new ConcurrentDictionary<string, JobResult> (); var intentFilter = new IntentFilter (TaskBinder.JobEnded){Priority = (int)IntentFilterPriority.HighPriority}; Xamarin.Forms.Forms.Context.RegisterReceiver (this, intentFilter); } var temp = new JobResult { IsRunning = true }; _Jobs.AddOrUpdate(task.JobID, temp, (z, x) => { return temp; }); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our TextBox from the layout resource, _txtMsg = FindViewById<TextView>(Resource.Id.txtMessage); IntentFilter filter = new IntentFilter(Intent.ActionSend); MessageReciever receiver = new MessageReciever(this); LocalBroadcastManager.GetInstance(this).RegisterReceiver(receiver, filter); }
public override Task<OAuthResult> Login(string oauthLoginUrl) { logger.d (LOG_TAG, "Got oauth url = " + oauthLoginUrl, null); Bundle data = new Bundle (); data.PutString ("url", oauthLoginUrl); data.PutString ("title", "Login"); Intent i = new Intent (this.appContext, typeof(FHOAuthIntent)); receiver = new OAuthURLRedirectReceiver (this); IntentFilter filter = new IntentFilter (FHOAuthWebview.BROADCAST_ACTION_FILTER); this.appContext.RegisterReceiver (this.receiver, filter); i.PutExtra ("settings", data); i.AddFlags (ActivityFlags.NewTask); this.appContext.StartActivity (i); return tcs.Task; }
public override void OnResume () { base.OnResume (); UpdateNotesTab (); // Start listening for time updates to adjust "now" bar. TIME_TICK is // triggered once per minute, which is how we move the bar over time. IntentFilter filter = new IntentFilter (); filter.AddAction (Intent.ActionPackageAdded); filter.AddAction (Intent.ActionPackageRemoved); filter.AddAction (Intent.ActionPackageReplaced); filter.AddDataScheme ("package"); Activity.RegisterReceiver (packageChangesReceiver, filter); }
public override void OnCreate() { base.OnCreate(); _context = ApplicationContext; // TODO: Probably creates a memory leak. BootstrapApp(); // Set player plugin directory path ApplicationInfo appInfo = PackageManager.GetApplicationInfo(PackageName, 0); Sessions.Player.Player.PluginDirectoryPath = appInfo.NativeLibraryDir; try { Console.WriteLine("Application - Registering ConnectionChangeReceiver..."); _connectionChangeReceiver = new ConnectionChangeReceiver(); IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"); filter.AddCategory(Intent.CategoryDefault); RegisterReceiver(_connectionChangeReceiver, filter); } catch (Exception ex) { Console.WriteLine("Application - Error: Failed to setup connection change receiver! {0}", ex); } try { Console.WriteLine("Application - Registering LockReceiver..."); var intentFilter = new IntentFilter(); intentFilter.AddAction(Intent.ActionScreenOff); intentFilter.AddAction(Intent.ActionScreenOn); intentFilter.AddAction(Intent.ActionUserPresent); intentFilter.AddCategory(Intent.CategoryDefault); _lockReceiver = new LockReceiver(); RegisterReceiver(_lockReceiver, intentFilter); } catch (Exception ex) { Console.WriteLine("Application - Error: Failed to setup lock receiver! {0}", ex); } //#if __ANDROID_16__ // if (((int)global::Android.OS.Build.VERSION.SdkInt) >= 16) { // _discoveryService = new AndroidDiscoveryService(); // _discoveryService.StartDiscovery(); // _discoveryService.DiscoverPeers(); // } //#endif }
private void SetupWifiDirect() { _intentFilter = new IntentFilter(); _intentFilter.AddAction(WifiP2pManager.WifiP2pStateChangedAction); _intentFilter.AddAction(WifiP2pManager.WifiP2pPeersChangedAction); _intentFilter.AddAction(WifiP2pManager.WifiP2pConnectionChangedAction); _intentFilter.AddAction(WifiP2pManager.WifiP2pThisDeviceChangedAction); _actionListener = new ActionListener(); _peerListListener = new PeerListListener(); _wifiManager = (WifiP2pManager)SessionsApplication.Context.GetSystemService(Context.WifiP2pService); _wifiChannel = _wifiManager.Initialize(SessionsApplication.Context, SessionsApplication.Context.MainLooper, null); _wifiDirectReceiver = new WifiDirectReceiver(); _wifiDirectReceiver.SetManager(_wifiManager, _wifiChannel, _peerListListener); SessionsApplication.Context.RegisterReceiver(_wifiDirectReceiver, _intentFilter); }
protected override void OnCreate(Bundle bundle) { base.OnCreate (bundle); var c = new Com.Loopj.Android.Http.AsyncHttpClient (); ROXIMITYEngine.StartEngineWithOptions(this.ApplicationContext, Resource.Drawable.notification_template_icon_bg, null, this, null); _receiver = new BeaconBrodcast (); var intentFilter = new IntentFilter (); intentFilter.AddAction (ROXConsts.MessageFired); intentFilter.AddAction (ROXConsts.BeaconRangeUpdate); RegisterReceiver (_receiver, intentFilter); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); }
/// <summary> /// OnCreate called when the activity is launched from cold or after the app /// has been killed due to a higher priority app needing the memory /// </summary> /// <param name='savedInstanceState'> /// Saved instance state. /// </param> protected override void OnCreate (Bundle savedInstanceState) { RequestWindowFeature(WindowFeatures.NoTitle); base.OnCreate(savedInstanceState); IntentFilter filter = new IntentFilter(); filter.AddAction(Intent.ActionScreenOff); filter.AddAction(Intent.ActionScreenOn); filter.AddAction(Intent.ActionUserPresent); screenReceiver = new ScreenReceiver(); RegisterReceiver(screenReceiver, filter); _orientationListener = new OrientationListener(this); Game.Activity = this; }
protected override void OnResume() { base.OnResume (); // Handle any Google Play services errors if (PlayServicesUtils.IsGooglePlayStoreAvailable (this)) { PlayServicesUtils.HandleAnyPlayServicesError (this); } // Use local broadcast manager to receive registration events to update the channel IntentFilter channelIdUpdateFilter; channelIdUpdateFilter = new IntentFilter (); channelIdUpdateFilter.AddAction (UrbanAirshipReceiver.ACTION_CHANNEL_UPDATED); LocalBroadcastManager.GetInstance (this).RegisterReceiver (channelIdUpdateReceiver, channelIdUpdateFilter); // Update the channel field UpdateChannelIdField (); }
private void initBluetooth() { receiver = new BluetoothReceiver(); filter = new IntentFilter(Android.Bluetooth.BluetoothAdapter.ActionStateChanged); Android.App.Application.Context.RegisterReceiver(receiver, filter); }
/// <summary> /// Creates a new instance of <see cref="RegistrationSwitchableBroadcastReceiver"/> class from the specified <see cref="Intent"/> MIME type. /// </summary> /// <param name="filter">MIME type for identifying <see cref="Intent"/> information</param> public RegistrationSwitchableBroadcastReceiver(string filter) { intentFilter = new IntentFilter(filter); }
private void RegisterReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter) { _context.RegisterReceiver(broadcastReceiver, intentFilter); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); mStatusTv = (TextView)FindViewById(Resource.Id.tv_status); mActivateBtn = (Button)FindViewById(Resource.Id.btn_enable); mPairedBtn = (Button)FindViewById(Resource.Id.btn_view_paired); mScanBtn = (Button)FindViewById(Resource.Id.btn_scan); mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; mProgressDlg = new ProgressDialog(this); mProgressDlg.SetMessage("Scanning..."); mProgressDlg.SetCancelable(false); IntentFilter filter = new IntentFilter(); filter.AddAction(BluetoothAdapter.ActionStateChanged); filter.AddAction(BluetoothDevice.ActionFound); filter.AddAction(BluetoothAdapter.ActionDiscoveryStarted); filter.AddAction(BluetoothAdapter.ActionDiscoveryFinished); broadcastReceiver = new BluetoothBroadcastReceiver(() => { showToast("Enabled"); showEnabled(); }, () => { mProgressDlg.Show(); }, mDeviceList); RegisterReceiver(broadcastReceiver, filter); if (mBluetoothAdapter == null) { showUnsupported(); } else { mPairedBtn.Click += (sender, e) => { var pairedDevices = mBluetoothAdapter.BondedDevices; if (pairedDevices == null || pairedDevices.Count == 0) { showToast("No Paired Devices Found"); } else { IList <IParcelable> list = new List <IParcelable>(); foreach (var device in pairedDevices) { list.Add(device); } Intent intent = new Intent(this, typeof(DeviceListActivity)); intent.PutParcelableArrayListExtra("device.list", list); StartActivity(intent); } }; mScanBtn.Click += (sender, e) => { if (mBluetoothAdapter.IsDiscovering) { // cancel the discovery if it has already started mBluetoothAdapter.CancelDiscovery(); } if (mBluetoothAdapter.StartDiscovery()) { // bluetooth has started discovery } }; mActivateBtn.Click += (sender, e) => { if (mBluetoothAdapter.IsEnabled) { mBluetoothAdapter.Disable(); showDisabled(); } else { Intent intent = new Intent(BluetoothAdapter.ActionRequestEnable); StartActivityForResult(intent, 1000); } }; if (mBluetoothAdapter.IsEnabled) { showEnabled(); } else { showDisabled(); } } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Log.Debug(TAG, "OnCreate"); //create a new kid //RandomString rString = new RandomString(); //k_id = RandomString.GetRandomString(32); //Log.Debug(TAG, "session_id = " + k_id); context = Android.App.Application.Context; //get virtual keyboard imm = (InputMethodManager)GetSystemService(Activity.InputMethodService); //get default prefs = PreferenceManager.GetDefaultSharedPreferences(this); //pda type pda_type = prefs.GetInt("PDA_TYPE", 0); //default port web_soap_port = prefs.GetString("WEB_SOAP_PORT", "8484"); //save current kid //editor = prefs.Edit(); //editor.PutString("CURRENT_K_ID", k_id); //editor.Apply(); SetContentView(Resource.Layout.activity_main); //Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); myToolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(myToolbar); /*FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab); * fab.Click += FabOnClick;*/ DrawerLayout drawer = FindViewById <DrawerLayout>(Resource.Id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, myToolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close); drawer.AddDrawerListener(toggle); toggle.SyncState(); NavigationView navigationView = FindViewById <NavigationView>(Resource.Id.nav_view); navigationView.SetNavigationItemSelectedListener(this); View headerLayout = navigationView.GetHeaderView(0); empID = headerLayout.FindViewById <TextView>(Resource.Id.empId); menuItemLogin = navigationView.Menu.FindItem(Resource.Id.nav_login); menuItemLogout = navigationView.Menu.FindItem(Resource.Id.nav_logout); //menuItemReceiveGoods = navigationView.Menu.FindItem(Resource.Id.nav_receiving); //menuItemShipment = navigationView.Menu.FindItem(Resource.Id.nav_shipment); menuItemSearch = navigationView.Menu.FindItem(Resource.Id.nav_search); menuItemAllocationSendMsg = navigationView.Menu.FindItem(Resource.Id.nav_allocation_send_msg); menuItemAllocation = navigationView.Menu.FindItem(Resource.Id.nav_allocation); menuItemEnteringWareHouse = navigationView.Menu.FindItem(Resource.Id.nav_entering_warehouse); menuItemProductionStorage = navigationView.Menu.FindItem(Resource.Id.nav_production_storage); //menuItemProductionStorage = navigationView.Menu.FindItem(Resource.Id.nav_production_storage); //menuItemReceivingInspection = navigationView.Menu.FindItem(Resource.Id.nav_receiving_inspection); if (!isLogin) { Fragment fragment = new LoginFragment(); fragmentManager = this.FragmentManager; FragmentTransaction fragmentTx = fragmentManager.BeginTransaction(); //fragmentTx.Add(Resource.Id.flContent, fragment); fragmentTx.Replace(Resource.Id.flContent, fragment); fragmentTx.Commit(); } //broadcast receiver if (!isRegister) { IntentFilter filter = new IntentFilter(); mReceiver = new MyBoradcastReceiver(); filter.AddAction(Constants.SOAP_CONNECTION_FAIL); filter.AddAction(Constants.ACTION_SOCKET_TIMEOUT); filter.AddAction(Constants.ACTION_LOGIN_FAIL); filter.AddAction(Constants.ACTION_LOGIN_SUCCESS); filter.AddAction(Constants.ACTION_LOGOUT_ACTION); filter.AddAction(Constants.ACTION_SETTING_PDA_TYPE_ACTION); filter.AddAction(Constants.ACTION_SETTING_WEB_SOAP_PORT_ACTION); //filter.AddAction(Constants.ACTION_ENTERING_WAREHOUSE_INTO_STOCK_SHOW_DIALOG); filter.AddAction(Constants.ACTION_SEARCH_MENU_SHOW_ACTION); filter.AddAction(Constants.ACTION_SEARCH_MENU_HIDE_ACTION); filter.AddAction(Constants.ACTION_RESET_TITLE_PART_IN_STOCK); RegisterReceiver(mReceiver, filter); isRegister = true; } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.bt_selection); Title = "Choose bluetooth device..."; _btReceiver.DeviceReceived += OnDeviceReceived; _progressDialog = new ProgressDialog(ApplicationContext); var filter = new IntentFilter(BluetoothDevice.ActionFound); RegisterReceiver(_btReceiver, filter); var filter2 = new IntentFilter(BluetoothAdapter.ActionDiscoveryStarted); RegisterReceiver(_btReceiverStart, filter2); _arrayAdapter = new ArrayAdapter <string>(this, Resource.Layout.bt_selection_item); _arrayDevice = new List <BluetoothDevice>(); ListView lv = (ListView)FindViewById(Resource.Id.bt_selection_list); lv.Adapter = _arrayAdapter; lv.ItemClick += Lv_ItemClick; lv.TextFilterEnabled = true; if (_bluetoothAdapter == null) { Toast.MakeText(ApplicationContext, "No bluetooth adapter...", ToastLength.Long).Show(); } else { if (!_bluetoothAdapter.IsEnabled) { var enableBtIntent = new Intent( BluetoothAdapter.ActionRequestEnable); StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } RegisterReceiver(_btReceiver, filter); var pairedDevices = _bluetoothAdapter.BondedDevices; if (pairedDevices.Count > 0) { foreach (var device in pairedDevices) { /* mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); + mArrayDevice.add(device); */ } } _bluetoothAdapter.StartDiscovery(); } }
protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); if (Intent != null && InstanceAlreadyStarted && (Intent.Action == Intent.ActionView || Intent.Action == Intent.ActionSend)) { HandleImportFile(Intent); Finish(); return; } Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState); Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity = this; _config = new DVBTTelevizorConfiguration(); #if DEBUG _config.ShowServiceMenu = true; _config.ScanEPG = true; _config.EnableLogging = true; //_config.AutoInitAfterStart = false; #endif InitLogging(); _loggingService.Info("DVBTTelevizor starting"); // workaround for not using FileProvider (necessary for file sharing): // https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.SetVmPolicy(builder.Build()); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); // prevent sleep: Window window = (Forms.Context as Activity).Window; window.AddFlags(WindowManagerFlags.KeepScreenOn); // https://stackoverflow.com/questions/39248138/how-to-hide-bottom-bar-of-android-back-home-in-xamarin-forms _defaultUiOptions = (int)Window.DecorView.SystemUiVisibility; _fullscreenUiOptions = _defaultUiOptions; _fullscreenUiOptions |= (int)SystemUiFlags.LowProfile; _fullscreenUiOptions |= (int)SystemUiFlags.Fullscreen; _fullscreenUiOptions |= (int)SystemUiFlags.HideNavigation; _fullscreenUiOptions |= (int)SystemUiFlags.ImmersiveSticky; if (_config.Fullscreen) { SetFullScreen(true); } try { UsbManager manager = (UsbManager)GetSystemService(Context.UsbService); var usbReciever = new USBBroadcastReceiverSystem(); var intentFilter = new IntentFilter(UsbManager.ActionUsbDeviceAttached); var intentFilter2 = new IntentFilter(UsbManager.ActionUsbDeviceDetached); RegisterReceiver(usbReciever, intentFilter); RegisterReceiver(usbReciever, intentFilter2); usbReciever.UsbAttachedOrDetached += CheckIfUsbAttachedOrDetached; } catch (Exception ex) { _loggingService.Error(ex, "Error while initializing UsbManager"); } #if TestingDVBTDriverManager _driverManager = new TestingDVBTDriverManager(); #else _driverManager = new DVBTDriverManager(_loggingService, _config); #endif _notificationHelper = new NotificationHelper(this); _app = new App(_loggingService, _config, _driverManager); LoadApplication(_app); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_Init, (message) => { InitDriver(); }); MessagingCenter.Subscribe <SettingsPage>(this, BaseViewModel.MSG_CheckBatterySettings, (sender) => { try { var pm = (PowerManager)Android.App.Application.Context.GetSystemService(Context.PowerService); bool ignoring = pm.IsIgnoringBatteryOptimizations(AppInfo.PackageName); if (!ignoring) { MessagingCenter.Send <string>(string.Empty, BaseViewModel.MSG_RequestBatterySettings); } } catch (Exception ex) { _loggingService.Error(ex); } }); MessagingCenter.Subscribe <SettingsPage>(this, BaseViewModel.MSG_SetBatterySettings, (sender) => { try { var intent = new Intent(); intent.SetAction(Android.Provider.Settings.ActionIgnoreBatteryOptimizationSettings); intent.SetFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(intent); } catch (Exception ex) { _loggingService.Error(ex); } }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_ToastMessage, (message) => { ShowToastMessage(message); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_LongToastMessage, (message) => { ShowToastMessage(message, 8000); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_EnableFullScreen, (msg) => { SetFullScreen(true); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_DisableFullScreen, (msg) => { SetFullScreen(false); }); MessagingCenter.Subscribe <MainPage, PlayStreamInfo>(this, BaseViewModel.MSG_PlayInBackgroundNotification, (sender, playStreamInfo) => { Device.BeginInvokeOnMainThread(() => { Task.Run(async() => await ShowPlayingNotification(playStreamInfo)); }); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_StopPlayInBackgroundNotification, (sender) => { Device.BeginInvokeOnMainThread(() => { StopPlayingNotification(); }); }); MessagingCenter.Subscribe <string>(this, BaseViewModel.MSG_ShareFile, (fileName) => { Device.BeginInvokeOnMainThread(() => { Task.Run(async() => await ShareFile(fileName)); }); }); InstanceAlreadyStarted = true; if (Intent != null && InstanceAlreadyStarted && (Intent.Action == Intent.ActionView || Intent.Action == Intent.ActionSend)) { HandleImportFile(Intent); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.open_db_selection); var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.mytoolbar); SetSupportActionBar(toolbar); SupportActionBar.Title = GetString(Resource.String.select_database); //only load the AppTask if this is the "first" OnCreate (not because of kill/resume, i.e. savedInstanceState==null) // and if the activity is not launched from history (i.e. recent tasks) because this would mean that // the Activity was closed already (user cancelling the task or task complete) but is restarted due recent tasks. // Don't re-start the task (especially bad if tak was complete already) if (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory)) { AppTask = new NullTask(); } else { AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent); } _adapter = new OpenDatabaseAdapter(this); var gridView = FindViewById <GridView>(Resource.Id.gridview); gridView.Adapter = _adapter; if (!string.IsNullOrEmpty(Intent.GetStringExtra(Util.KeyFilename))) { IOConnectionInfo ioc = new IOConnectionInfo(); Util.SetIoConnectionFromIntent(ioc, Intent); if (App.Kp2a.TrySelectCurrentDb(ioc)) { if (!OpenAutoExecEntries(App.Kp2a.CurrentDb)) { LaunchingOther = true; AppTask.CanActivateSearchViewOnStart = true; AppTask.LaunchFirstGroupActivity(this); } } else { //forward to password activity Intent i = new Intent(this, typeof(PasswordActivity)); Util.PutIoConnectionToIntent(ioc, i); i.PutExtra(PasswordActivity.KeyKeyfile, i.GetStringExtra(PasswordActivity.KeyKeyfile)); i.PutExtra(PasswordActivity.KeyPassword, i.GetStringExtra(PasswordActivity.KeyPassword)); LaunchingOther = true; StartActivityForResult(i, ReqCodeOpenNewDb); } } else { if (Intent.Action == Intent.ActionView) { GetIocFromViewIntent(Intent); } else if (Intent.Action == Intent.ActionSend) { AppTask = new SearchUrlTask { UrlToSearchFor = Intent.GetStringExtra(Intent.ExtraText) }; } } _intentReceiver = new MyBroadcastReceiver(this); IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.DatabaseLocked); RegisterReceiver(_intentReceiver, filter); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Setup the window RequestWindowFeature(WindowFeatures.IndeterminateProgress); SetContentView(Resource.Layout.device_list); // Set result CANCELED incase the user backs out SetResult(Result.Canceled); // Initialize the button to perform device discovery var scanButton = FindViewById <Button> (Resource.Id.button_scan); scanButton.Click += (sender, e) => { DoDiscovery(); (sender as View).Visibility = ViewStates.Gone; }; // Initialize array adapters. One for already paired devices and // one for newly discovered devices pairedDevicesArrayAdapter = new ArrayAdapter <string> (this, Resource.Layout.device_name); newDevicesArrayAdapter = new ArrayAdapter <string> (this, Resource.Layout.device_name); // Find and set up the ListView for paired devices var pairedListView = FindViewById <ListView> (Resource.Id.paired_devices); pairedListView.Adapter = pairedDevicesArrayAdapter; pairedListView.ItemClick += DeviceListClick; // Find and set up the ListView for newly discovered devices var newDevicesListView = FindViewById <ListView> (Resource.Id.new_devices); newDevicesListView.Adapter = newDevicesArrayAdapter; newDevicesListView.ItemClick += DeviceListClick; // Register for broadcasts when a device is discovered receiver = new Receiver(this); var filter = new IntentFilter(BluetoothDevice.ActionFound); RegisterReceiver(receiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished); RegisterReceiver(receiver, filter); // Get the local Bluetooth adapter btAdapter = BluetoothAdapter.DefaultAdapter; // Get a set of currently paired devices var pairedDevices = btAdapter.BondedDevices; // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.Count > 0) { FindViewById <View> (Resource.Id.title_paired_devices).Visibility = ViewStates.Visible; foreach (var device in pairedDevices) { pairedDevicesArrayAdapter.Add(device.Name + "\n" + device.Address); } } else { String noDevices = Resources.GetText(Resource.String.none_paired); pairedDevicesArrayAdapter.Add(noDevices); } }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Kp2aLog.Log("Received intent to provide access to entry"); _stopOnLockBroadcastReceiver = new StopOnLockBroadcastReceiver(this); IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.DatabaseLocked); RegisterReceiver(_stopOnLockBroadcastReceiver, filter); if ((intent.Action == Intents.ShowNotification) || (intent.Action == Intents.UpdateKeyboard)) { String uuidBytes = intent.GetStringExtra(EntryActivity.KeyEntry); String searchUrl = intent.GetStringExtra(SearchUrlTask.UrlToSearchKey); PwUuid entryId = PwUuid.Zero; if (uuidBytes != null) { entryId = new PwUuid(MemUtil.HexStringToByteArray(uuidBytes)); } PwEntryOutput entry; try { if ((App.Kp2a.GetDb().LastOpenedEntry != null) && (entryId.Equals(App.Kp2a.GetDb().LastOpenedEntry.Uuid))) { entry = App.Kp2a.GetDb().LastOpenedEntry; } else { entry = new PwEntryOutput(App.Kp2a.GetDb().Entries[entryId], App.Kp2a.GetDb().KpDatabase); } } catch (Exception) { //seems like restarting the service happened after closing the DB StopSelf(); return(StartCommandResult.NotSticky); } if (intent.Action == Intents.ShowNotification) { //first time opening the entry -> bring up the notifications bool closeAfterCreate = intent.GetBooleanExtra(EntryActivity.KeyCloseAfterCreate, false); DisplayAccessNotifications(entry, closeAfterCreate, searchUrl); } else //UpdateKeyboard { #if !EXCLUDE_KEYBOARD //this action is received when the data in the entry has changed (e.g. by plugins) //update the keyboard data. //Check if keyboard is (still) available if (Keepass2android.Kbbridge.KeyboardData.EntryId == entry.Uuid.ToHexString()) { MakeAccessibleForKeyboard(entry, searchUrl); } #endif } } if (intent.Action == Intents.CopyStringToClipboard) { TimeoutCopyToClipboard(intent.GetStringExtra(_stringtocopy)); } if (intent.Action == Intents.ActivateKeyboard) { ActivateKp2aKeyboard(); } if (intent.Action == Intents.ClearNotificationsAndData) { ClearNotifications(); } return(StartCommandResult.RedeliverIntent); }
public void DisplayAccessNotifications(PwEntryOutput entry, bool closeAfterCreate, string searchUrl) { var hadKeyboardData = ClearNotifications(); String entryName = entry.OutputStrings.ReadSafe(PwDefs.TitleField); var bmp = Util.DrawableToBitmap(App.Kp2a.GetDb().DrawableFactory.GetIconDrawable(this, App.Kp2a.GetDb().KpDatabase, entry.Entry.IconId, entry.Entry.CustomIconUuid, false)); if (!(((entry.Entry.CustomIconUuid != null) && (!entry.Entry.CustomIconUuid.Equals(PwUuid.Zero)))) && PreferenceManager.GetDefaultSharedPreferences(this).GetString("IconSetKey", PackageName) == PackageName) { Color drawingColor = new Color(189, 189, 189); bmp = Util.ChangeImageColor(bmp, drawingColor); } Bitmap entryIcon = Util.MakeLargeIcon(bmp, this); ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this); var notBuilder = new PasswordAccessNotificationBuilder(this, _notificationManager); if (prefs.GetBoolean(GetString(Resource.String.CopyToClipboardNotification_key), Resources.GetBoolean(Resource.Boolean.CopyToClipboardNotification_default))) { if (entry.OutputStrings.ReadSafe(PwDefs.PasswordField).Length > 0) { notBuilder.AddPasswordAccess(); } if (entry.OutputStrings.ReadSafe(PwDefs.UserNameField).Length > 0) { notBuilder.AddUsernameAccess(); } } bool hasKeyboardDataNow = false; if (prefs.GetBoolean(GetString(Resource.String.UseKp2aKeyboard_key), Resources.GetBoolean(Resource.Boolean.UseKp2aKeyboard_default))) { //keyboard hasKeyboardDataNow = MakeAccessibleForKeyboard(entry, searchUrl); if (hasKeyboardDataNow) { notBuilder.AddKeyboardAccess(); if (prefs.GetBoolean("kp2a_switch_rooted", false)) { //switch rooted bool onlySwitchOnSearch = prefs.GetBoolean(GetString(Resource.String.OpenKp2aKeyboardAutomaticallyOnlyAfterSearch_key), false); if (closeAfterCreate || (!onlySwitchOnSearch)) { ActivateKp2aKeyboard(); } } else { //if the app is about to be closed again (e.g. after searching for a URL and returning to the browser: // automatically bring up the Keyboard selection dialog if ((closeAfterCreate) && prefs.GetBoolean(GetString(Resource.String.OpenKp2aKeyboardAutomatically_key), Resources.GetBoolean(Resource.Boolean.OpenKp2aKeyboardAutomatically_default))) { ActivateKp2aKeyboard(); } } } } if ((!hasKeyboardDataNow) && (hadKeyboardData)) { ClearKeyboard(true); //this clears again and then (this is the point) broadcasts that we no longer have keyboard data } _numElementsToWaitFor = notBuilder.CreateNotifications(entryName, entryIcon); if (_numElementsToWaitFor == 0) { StopSelf(); return; } //register receiver to get notified when notifications are discarded in which case we can shutdown the service _notificationDeletedBroadcastReceiver = new NotificationDeletedBroadcastReceiver(this); IntentFilter deletefilter = new IntentFilter(); deletefilter.AddAction(ActionNotificationCancelled); RegisterReceiver(_notificationDeletedBroadcastReceiver, deletefilter); }
private static void AddBrowsableTags(IntentFilter intentFilter) { intentFilter.AddChild(new Category("android.intent.category.BROWSABLE")); intentFilter.AddChild(new Category("android.intent.category.DEFAULT")); intentFilter.AddChild(new Action("android.intent.action.VIEW")); }
public virtual void OnReceived(IDictionary <string, object> parameters) { System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived"); if ((parameters.TryGetValue(SilentKey, out object silent) && (silent.ToString() == "true" || silent.ToString() == "1"))) { return; } Context context = Application.Context; int notifyId = 0; string title = context.ApplicationInfo.LoadLabel(context.PackageManager); var message = string.Empty; var tag = string.Empty; if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTextKey) && parameters.TryGetValue(FirebasePushNotificationManager.NotificationContentTextKey, out object notificationContentText)) { message = notificationContentText.ToString(); } else if (parameters.TryGetValue(AlertKey, out object alert)) { message = $"{alert}"; } else if (parameters.TryGetValue(BodyKey, out object body)) { message = $"{body}"; } else if (parameters.TryGetValue(MessageKey, out object messageContent)) { message = $"{messageContent}"; } else if (parameters.TryGetValue(SubtitleKey, out object subtitle)) { message = $"{subtitle}"; } else if (parameters.TryGetValue(TextKey, out object text)) { message = $"{text}"; } if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTitleKey) && parameters.TryGetValue(FirebasePushNotificationManager.NotificationContentTitleKey, out object notificationContentTitle)) { title = notificationContentTitle.ToString(); } else if (parameters.TryGetValue(TitleKey, out object titleContent)) { if (!string.IsNullOrEmpty(message)) { title = $"{titleContent}"; } else { message = $"{titleContent}"; } } if (parameters.TryGetValue(IdKey, out object id)) { try { notifyId = Convert.ToInt32(id); } catch (Exception ex) { // Keep the default value of zero for the notify_id, but log the conversion problem. System.Diagnostics.Debug.WriteLine($"Failed to convert {id} to an integer {ex}"); } } if (parameters.TryGetValue(TagKey, out object tagContent)) { tag = tagContent.ToString(); } try { if (parameters.TryGetValue(SoundKey, out object sound)) { var soundName = sound.ToString(); int soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName); if (soundResId == 0 && soundName.IndexOf(".") != -1) { soundName = soundName.Substring(0, soundName.LastIndexOf('.')); soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName); } FirebasePushNotificationManager.SoundUri = new Android.Net.Uri.Builder() .Scheme(ContentResolver.SchemeAndroidResource) .Path($"{context.PackageName}/{soundResId}") .Build(); } } catch (Resources.NotFoundException ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } if (FirebasePushNotificationManager.SoundUri == null) { FirebasePushNotificationManager.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); } try { if (parameters.TryGetValue(IconKey, out object icon) && icon != null) { try { FirebasePushNotificationManager.IconResource = context.Resources.GetIdentifier(icon.ToString(), "drawable", Application.Context.PackageName); } catch (Resources.NotFoundException ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } if (FirebasePushNotificationManager.IconResource == 0) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; } else { string name = context.Resources.GetResourceName(FirebasePushNotificationManager.IconResource); if (name == null) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; } } } catch (Resources.NotFoundException ex) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; System.Diagnostics.Debug.WriteLine(ex.ToString()); } if (parameters.TryGetValue(ColorKey, out object color) && color != null) { try { FirebasePushNotificationManager.Color = Color.ParseColor(color.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to parse color {ex}"); } } Intent resultIntent = typeof(Activity).IsAssignableFrom(FirebasePushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, FirebasePushNotificationManager.NotificationActivityType) : (FirebasePushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, FirebasePushNotificationManager.DefaultNotificationActivityType)); Bundle extras = new Bundle(); foreach (var p in parameters) { extras.PutString(p.Key, p.Value.ToString()); } if (extras != null) { extras.PutInt(ActionNotificationIdKey, notifyId); extras.PutString(ActionNotificationTagKey, tag); resultIntent.PutExtras(extras); } if (FirebasePushNotificationManager.NotificationActivityFlags != null) { resultIntent.SetFlags(FirebasePushNotificationManager.NotificationActivityFlags.Value); } int requestCode = new Java.Util.Random().NextInt(); var pendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent); var chanId = FirebasePushNotificationManager.DefaultNotificationChannelId; if (parameters.TryGetValue(ChannelIdKey, out object channelId) && channelId != null) { chanId = $"{channelId}"; } var notificationBuilder = new NotificationCompat.Builder(context, chanId) .SetSmallIcon(FirebasePushNotificationManager.IconResource) .SetContentTitle(title) .SetContentText(message) .SetAutoCancel(true) .SetContentIntent(pendingIntent); if (FirebasePushNotificationManager.LargeIconResource > 0) { try { var largeIcon = BitmapFactory.DecodeResource(context.Resources, FirebasePushNotificationManager.LargeIconResource); notificationBuilder.SetLargeIcon(largeIcon); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } var deleteIntent = new Intent(context, typeof(PushNotificationDeletedReceiver)); var pendingDeleteIntent = PendingIntent.GetBroadcast(context, requestCode, deleteIntent, PendingIntentFlags.CancelCurrent); notificationBuilder.SetDeleteIntent(pendingDeleteIntent); if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.O) { if (parameters.TryGetValue(PriorityKey, out object priority) && priority != null) { var priorityValue = $"{priority}"; if (!string.IsNullOrEmpty(priorityValue)) { switch (priorityValue.ToLower()) { case "max": notificationBuilder.SetPriority(NotificationCompat.PriorityMax); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; case "high": notificationBuilder.SetPriority(NotificationCompat.PriorityHigh); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; case "default": notificationBuilder.SetPriority(NotificationCompat.PriorityDefault); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; case "low": notificationBuilder.SetPriority(NotificationCompat.PriorityLow); break; case "min": notificationBuilder.SetPriority(NotificationCompat.PriorityMin); break; default: notificationBuilder.SetPriority(NotificationCompat.PriorityDefault); notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); break; } } else { notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); } } else { notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); } try { notificationBuilder.SetSound(FirebasePushNotificationManager.SoundUri); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to set sound {ex}"); } } // Try to resolve (and apply) localized parameters ResolveLocalizedParameters(notificationBuilder, parameters); if (FirebasePushNotificationManager.Color != null) { notificationBuilder.SetColor(FirebasePushNotificationManager.Color.Value); } if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean) { // Using BigText notification style to support long message var style = new NotificationCompat.BigTextStyle(); style.BigText(message); notificationBuilder.SetStyle(style); } string category = string.Empty; if (parameters.TryGetValue(CategoryKey, out object categoryContent)) { category = categoryContent.ToString(); } if (parameters.TryGetValue(ActionKey, out object actionContent)) { category = actionContent.ToString(); } var notificationCategories = CrossFirebasePushNotification.Current?.GetUserNotificationCategories(); if (notificationCategories != null && notificationCategories.Length > 0) { IntentFilter intentFilter = null; foreach (var userCat in notificationCategories) { if (userCat != null && userCat.Actions != null && userCat.Actions.Count > 0) { foreach (var action in userCat.Actions) { var aRequestCode = Guid.NewGuid().GetHashCode(); if (userCat.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase)) { Intent actionIntent = null; PendingIntent pendingActionIntent = null; if (action.Type == NotificationActionType.Foreground) { actionIntent = typeof(Activity).IsAssignableFrom(FirebasePushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, FirebasePushNotificationManager.NotificationActivityType) : (FirebasePushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, FirebasePushNotificationManager.DefaultNotificationActivityType)); if (FirebasePushNotificationManager.NotificationActivityFlags != null) { actionIntent.SetFlags(FirebasePushNotificationManager.NotificationActivityFlags.Value); } extras.PutString(ActionIdentifierKey, action.Id); actionIntent.PutExtras(extras); pendingActionIntent = PendingIntent.GetActivity(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent); } else { actionIntent = new Intent(context, typeof(PushNotificationActionReceiver)); extras.PutString(ActionIdentifierKey, action.Id); actionIntent.PutExtras(extras); pendingActionIntent = PendingIntent.GetBroadcast(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent); } notificationBuilder.AddAction(new NotificationCompat.Action.Builder(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent).Build()); } } } } } OnBuildNotification(notificationBuilder, parameters); NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); notificationManager.Notify(tag, notifyId, notificationBuilder.Build()); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SupportActionBar.SetHomeButtonEnabled(true); SupportActionBar.SetDisplayShowHomeEnabled(true); SupportActionBar.SetDisplayHomeAsUpEnabled(true); // Setup the window SetContentView(Resource.Layout.device_list); // Set result CANCELED incase the user backs out SetResult(Android.App.Result.Canceled); _activityCommon = new ActivityCommon(this); _appDataDir = Intent.GetStringExtra(ExtraAppDataDir); // Initialize the button to perform device discovery _scanButton = FindViewById <Button>(Resource.Id.button_scan); _scanButton.Click += (sender, e) => { DoDiscovery(); _scanButton.Enabled = false; }; // Initialize array adapters. One for already paired devices and // one for newly discovered devices _pairedDevicesArrayAdapter = new ArrayAdapter <string> (this, Resource.Layout.device_name); _newDevicesArrayAdapter = new ArrayAdapter <string> (this, Resource.Layout.device_name); // Find and set up the ListView for paired devices var pairedListView = FindViewById <ListView> (Resource.Id.paired_devices); pairedListView.Adapter = _pairedDevicesArrayAdapter; pairedListView.ItemClick += DeviceListClick; // Find and set up the ListView for newly discovered devices var newDevicesListView = FindViewById <ListView> (Resource.Id.new_devices); newDevicesListView.Adapter = _newDevicesArrayAdapter; newDevicesListView.ItemClick += DeviceListClick; // Register for broadcasts when a device is discovered _receiver = new Receiver(this); var filter = new IntentFilter(BluetoothDevice.ActionFound); RegisterReceiver(_receiver, filter); // Register for broadcasts when a device name changed _receiver = new Receiver(this); filter = new IntentFilter(BluetoothDevice.ActionNameChanged); RegisterReceiver(_receiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished); RegisterReceiver(_receiver, filter); // Get the local Bluetooth adapter _btAdapter = BluetoothAdapter.DefaultAdapter; // Get a set of currently paired devices var pairedDevices = _btAdapter.BondedDevices; // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.Count > 0) { foreach (var device in pairedDevices) { if (device == null) { continue; } try { ParcelUuid[] uuids = device.GetUuids(); if ((uuids == null) || (uuids.Any(uuid => SppUuid.CompareTo(uuid.Uuid) == 0))) { _pairedDevicesArrayAdapter.Add(device.Name + "\n" + device.Address); } } catch (Exception) { // ignored } } } else { if (_btAdapter.IsEnabled) { _pairedDevicesArrayAdapter.Add(Resources.GetText(Resource.String.none_paired)); } else { _pairedDevicesArrayAdapter.Add(Resources.GetText(Resource.String.bt_not_enabled)); } } }
public void DisplayAccessNotifications(PwEntryOutput entry, bool closeAfterCreate, string searchUrl) { var hadKeyboardData = ClearNotifications(); String entryName = entry.OutputStrings.ReadSafe(PwDefs.TitleField); ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this); var notBuilder = new PasswordAccessNotificationBuilder(this, _notificationManager); if (prefs.GetBoolean(GetString(Resource.String.CopyToClipboardNotification_key), Resources.GetBoolean(Resource.Boolean.CopyToClipboardNotification_default))) { if (entry.OutputStrings.ReadSafe(PwDefs.PasswordField).Length > 0) { notBuilder.AddPasswordAccess(); } if (entry.OutputStrings.ReadSafe(PwDefs.UserNameField).Length > 0) { notBuilder.AddUsernameAccess(); } } bool hasKeyboardDataNow = false; if (prefs.GetBoolean(GetString(Resource.String.UseKp2aKeyboard_key), Resources.GetBoolean(Resource.Boolean.UseKp2aKeyboard_default))) { //keyboard hasKeyboardDataNow = MakeAccessibleForKeyboard(entry, searchUrl); if (hasKeyboardDataNow) { notBuilder.AddKeyboardAccess(); if (closeAfterCreate && Keepass2android.Autofill.AutoFillService.IsAvailable && (!Keepass2android.Autofill.AutoFillService.IsRunning)) { if (!prefs.GetBoolean("has_asked_autofillservice", false)) { var i = new Intent(this, typeof(ActivateAutoFillActivity)); i.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask); StartActivity(i); prefs.Edit().PutBoolean("has_asked_autofillservice", true).Commit(); } else { ActivateKeyboardIfAppropriate(closeAfterCreate, prefs); } } else { ActivateKeyboardIfAppropriate(closeAfterCreate, prefs); } } } if ((!hasKeyboardDataNow) && (hadKeyboardData)) { ClearKeyboard(true); //this clears again and then (this is the point) broadcasts that we no longer have keyboard data } _numElementsToWaitFor = notBuilder.CreateNotifications(entryName); if (_numElementsToWaitFor == 0) { StopSelf(); return; } IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.CopyUsername); filter.AddAction(Intents.CopyPassword); filter.AddAction(Intents.CheckKeyboard); //register receiver to get notified when notifications are discarded in which case we can shutdown the service _notificationDeletedBroadcastReceiver = new NotificationDeletedBroadcastReceiver(this); IntentFilter deletefilter = new IntentFilter(); deletefilter.AddAction(ActionNotificationCancelled); RegisterReceiver(_notificationDeletedBroadcastReceiver, deletefilter); }
protected override void OnCreate(Bundle bundle) { _design.ApplyTheme(); base.OnCreate(bundle); //use FlagSecure to make sure the last (revealed) character of the password is not visible in recent apps if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean( GetString(Resource.String.ViewDatabaseSecure_key), true)) { Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure); } _ioc = App.Kp2a.GetDb().Ioc; if (_ioc == null) { Finish(); return; } SetContentView(Resource.Layout.QuickUnlock); var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.mytoolbar); SetSupportActionBar(toolbar); var collapsingToolbar = FindViewById <CollapsingToolbarLayout>(Resource.Id.collapsing_toolbar); collapsingToolbar.SetTitle(GetString(Resource.String.QuickUnlock_prefs)); if (App.Kp2a.GetDb().KpDatabase.Name != "") { FindViewById(Resource.Id.filename_label).Visibility = ViewStates.Visible; ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetDb().KpDatabase.Name; } else { if ( PreferenceManager.GetDefaultSharedPreferences(this) .GetBoolean(GetString(Resource.String.RememberRecentFiles_key), Resources.GetBoolean(Resource.Boolean.RememberRecentFiles_default))) { ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetFileStorage(_ioc).GetDisplayName(_ioc); } else { ((TextView)FindViewById(Resource.Id.filename_label)).Text = "*****"; } } TextView txtLabel = (TextView)FindViewById(Resource.Id.QuickUnlock_label); _quickUnlockLength = App.Kp2a.QuickUnlockKeyLength; txtLabel.Text = GetString(Resource.String.QuickUnlock_label, new Java.Lang.Object[] { _quickUnlockLength }); EditText pwd = (EditText)FindViewById(Resource.Id.QuickUnlock_password); pwd.SetEms(_quickUnlockLength); Util.MoveBottomBarButtons(Resource.Id.QuickUnlock_buttonLock, Resource.Id.QuickUnlock_button, Resource.Id.bottom_bar, this); Button btnUnlock = (Button)FindViewById(Resource.Id.QuickUnlock_button); btnUnlock.Click += (object sender, EventArgs e) => { OnUnlock(_quickUnlockLength, pwd); }; Button btnLock = (Button)FindViewById(Resource.Id.QuickUnlock_buttonLock); btnLock.Text = btnLock.Text.Replace("ß", "ss"); btnLock.Click += (object sender, EventArgs e) => { App.Kp2a.LockDatabase(false); Finish(); }; pwd.EditorAction += (sender, args) => { if ((args.ActionId == ImeAction.Done) || ((args.ActionId == ImeAction.ImeNull) && (args.Event.Action == KeyEventActions.Down))) { OnUnlock(_quickUnlockLength, pwd); } }; _intentReceiver = new QuickUnlockBroadcastReceiver(this); IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.DatabaseLocked); RegisterReceiver(_intentReceiver, filter); if ((int)Build.VERSION.SdkInt >= 23) { Kp2aLog.Log("requesting fingerprint permission"); RequestPermissions(new[] { Manifest.Permission.UseFingerprint }, FingerprintPermissionRequestCode); } else { } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter; if (mBluetoothAdapter == null) { // Device does not support Bluetooth } if (!mBluetoothAdapter.IsEnabled) { Intent enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable); int REQUEST_ENABLE_BT = 0; StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } // Register for broadcasts when a device is discovered receiver = new Receiver(this); var filter = new IntentFilter(BluetoothDevice.ActionFound); RegisterReceiver(receiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished); RegisterReceiver(receiver, filter); // Register for broadcasts when a device tries to pair filter = new IntentFilter(BluetoothDevice.ActionPairingRequest); RegisterReceiver(receiver, filter); // Get the local Bluetooth adapter btAdapter = BluetoothAdapter.DefaultAdapter; var scanButton = FindViewById <Button>(Resource.Id.button1); scanButton.Click += (sender, e) => { char[] blank = new char[1]; FindViewById <TextView>(Resource.Id.textView2).SetText(blank, 0, 0); receiver.HC05Found = false; DoDiscovery(); }; var aboutButton = FindViewById <Button>(Resource.Id.button2); aboutButton.Click += (sender, e) => { About(this); }; var closeButton = FindViewById <Button>(Resource.Id.button3); closeButton.Click += (sender, e) => { mBluetoothAdapter.Disable(); this.FinishAffinity(); }; }
/// <summary> /// This is the main thread for the Downloader. /// This thread is responsible for queuing up downloads and other goodness. /// </summary> /// <param name="intent"> /// The intent that was recieved. /// </param> protected override void OnHandleIntent(Intent intent) { Log.Debug(Tag, "DownloaderService.OnHandleIntent"); this.IsServiceRunning = true; try { var pendingIntent = (PendingIntent)intent.GetParcelableExtra(DownloaderServiceExtras.PendingIntent); if (null != pendingIntent) { this.downloadNotification.PendingIntent = pendingIntent; this.pPendingIntent = pendingIntent; } else if (null != this.pPendingIntent) { this.downloadNotification.PendingIntent = this.pPendingIntent; } else { Log.Debug(Tag, "LVLDL Downloader started in bad state without notification intent."); return; } // when the LVL check completes, a successful response will update the service if (IsLvlCheckRequired(this.packageInfo)) { this.UpdateLvl(this); return; } // get each download List <DownloadInfo> infos = DownloadsDatabase.GetDownloads(); this.BytesSoFar = 0; this.TotalLength = 0; this.fileCount = infos.Count(); foreach (DownloadInfo info in infos) { // We do an (simple) integrity check on each file, just to // make sure and to verify that the file matches the state if (info.Status == ExpansionDownloadStatus.Success && !Helpers.DoesFileExist(this, info.FileName, info.TotalBytes, true)) { info.Status = ExpansionDownloadStatus.None; info.CurrentBytes = 0; } // get aggregate data this.TotalLength += info.TotalBytes; this.BytesSoFar += info.CurrentBytes; } this.PollNetworkState(); if (this.connectionReceiver == null) { // We use this to track network state, such as when WiFi, Cellular, etc. is enabled // when downloads are paused or in progress. this.connectionReceiver = new InnerBroadcastReceiver(this); var intentFilter = new IntentFilter(ConnectivityManager.ConnectivityAction); intentFilter.AddAction(WifiManager.WifiStateChangedAction); this.RegisterReceiver(this.connectionReceiver, intentFilter); } // loop through all downloads and fetch them int types = Enum.GetValues(typeof(ApkExpansionPolicy.ExpansionFileType)).Length; for (int index = 0; index < types; index++) { DownloadInfo info = infos[index]; Log.Debug(Tag, "Starting download of " + info.FileName); long startingCount = info.CurrentBytes; if (info.Status != ExpansionDownloadStatus.Success) { var dt = new DownloadThread(info, this, this.downloadNotification); this.CancelAlarms(); this.ScheduleAlarm(ActiveThreadWatchdog); dt.Run(); this.CancelAlarms(); } DownloadsDatabase.UpdateFromDatabase(ref info); bool setWakeWatchdog = false; DownloaderState notifyStatus; switch (info.Status) { case ExpansionDownloadStatus.Forbidden: // the URL is out of date this.UpdateLvl(this); return; case ExpansionDownloadStatus.Success: this.BytesSoFar += info.CurrentBytes - startingCount; if (index < infos.Count() - 1) { continue; } DownloadsDatabase.UpdateMetadata(this.packageInfo.VersionCode, ExpansionDownloadStatus.None); this.downloadNotification.OnDownloadStateChanged(DownloaderState.Completed); return; case ExpansionDownloadStatus.FileDeliveredIncorrectly: // we may be on a network that is returning us a web page on redirect notifyStatus = DownloaderState.PausedNetworkSetupFailure; info.CurrentBytes = 0; DownloadsDatabase.UpdateDownload(info); setWakeWatchdog = true; break; case ExpansionDownloadStatus.PausedByApp: notifyStatus = DownloaderState.PausedByRequest; break; case ExpansionDownloadStatus.WaitingForNetwork: case ExpansionDownloadStatus.WaitingToRetry: notifyStatus = DownloaderState.PausedNetworkUnavailable; setWakeWatchdog = true; break; case ExpansionDownloadStatus.QueuedForWifi: case ExpansionDownloadStatus.QueuedForWifiOrCellularPermission: // look for more detail here notifyStatus = this.wifiManager != null && !this.wifiManager.IsWifiEnabled ? DownloaderState.PausedWifiDisabledNeedCellularPermission : DownloaderState.PausedNeedCellularPermission; setWakeWatchdog = true; break; case ExpansionDownloadStatus.Canceled: notifyStatus = DownloaderState.FailedCanceled; setWakeWatchdog = true; break; case ExpansionDownloadStatus.InsufficientSpaceError: notifyStatus = DownloaderState.FailedSdCardFull; setWakeWatchdog = true; break; case ExpansionDownloadStatus.DeviceNotFoundError: notifyStatus = DownloaderState.PausedSdCardUnavailable; setWakeWatchdog = true; break; default: notifyStatus = DownloaderState.Failed; break; } if (setWakeWatchdog) { this.ScheduleAlarm(WatchdogWakeTimer); } else { this.CancelAlarms(); } // failure or pause state this.downloadNotification.OnDownloadStateChanged(notifyStatus); return; } this.downloadNotification.OnDownloadStateChanged(DownloaderState.Completed); } catch (Exception ex) { Log.Error(Tag, ex.Message); Log.Error(Tag, ex.StackTrace); } finally { this.IsServiceRunning = false; } }
protected override void OnCreate(Bundle bundle) { _design.ApplyTheme(); base.OnCreate(bundle); //use FlagSecure to make sure the last (revealed) character of the password is not visible in recent apps Util.MakeSecureDisplay(this); _ioc = App.Kp2a.GetDbForQuickUnlock()?.Ioc; if (_ioc == null) { Finish(); return; } SetContentView(Resource.Layout.QuickUnlock); var toolbar = FindViewById <AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.mytoolbar); SetSupportActionBar(toolbar); var collapsingToolbar = FindViewById <CollapsingToolbarLayout>(Resource.Id.collapsing_toolbar); collapsingToolbar.SetTitle(GetString(Resource.String.QuickUnlock_prefs)); if (App.Kp2a.GetDbForQuickUnlock().KpDatabase.Name != "") { FindViewById(Resource.Id.filename_label).Visibility = ViewStates.Visible; ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetDbForQuickUnlock().KpDatabase.Name; } else { if ( PreferenceManager.GetDefaultSharedPreferences(this) .GetBoolean(GetString(Resource.String.RememberRecentFiles_key), Resources.GetBoolean(Resource.Boolean.RememberRecentFiles_default))) { ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetFileStorage(_ioc).GetDisplayName(_ioc); } else { ((TextView)FindViewById(Resource.Id.filename_label)).Text = "*****"; } } TextView txtLabel = (TextView)FindViewById(Resource.Id.QuickUnlock_label); _quickUnlockLength = App.Kp2a.QuickUnlockKeyLength; if (PreferenceManager.GetDefaultSharedPreferences(this) .GetBoolean(GetString(Resource.String.QuickUnlockHideLength_key), false)) { txtLabel.Text = GetString(Resource.String.QuickUnlock_label_secure); } else { txtLabel.Text = GetString(Resource.String.QuickUnlock_label, new Java.Lang.Object[] { _quickUnlockLength }); } EditText pwd = (EditText)FindViewById(Resource.Id.QuickUnlock_password); pwd.SetEms(_quickUnlockLength); Util.MoveBottomBarButtons(Resource.Id.QuickUnlock_buttonLock, Resource.Id.QuickUnlock_button, Resource.Id.bottom_bar, this); Button btnUnlock = (Button)FindViewById(Resource.Id.QuickUnlock_button); btnUnlock.Click += (object sender, EventArgs e) => { OnUnlock(pwd); }; Button btnLock = (Button)FindViewById(Resource.Id.QuickUnlock_buttonLock); btnLock.Text = btnLock.Text.Replace("ß", "ss"); btnLock.Click += (object sender, EventArgs e) => { App.Kp2a.Lock(false); Finish(); }; pwd.EditorAction += (sender, args) => { if ((args.ActionId == ImeAction.Done) || ((args.ActionId == ImeAction.ImeNull) && (args.Event.Action == KeyEventActions.Down))) { OnUnlock(pwd); } }; _intentReceiver = new QuickUnlockBroadcastReceiver(this); IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.DatabaseLocked); RegisterReceiver(_intentReceiver, filter); Util.SetNoPersonalizedLearning(FindViewById <EditText>(Resource.Id.QuickUnlock_password)); if (bundle != null) { numFailedAttempts = bundle.GetInt(NumFailedAttemptsKey, 0); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Setup the window RequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); SetContentView(R.Layouts.device_list); // Set result CANCELED in case the user backs out SetResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery var scanButton = (Button)FindViewById(R.Ids.button_scan); scanButton.Click += (s, x) => { doDiscovery(); ((View)s).SetVisibility(View.GONE); }; // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter <string>(this, R.Layouts.device_name); mNewDevicesArrayAdapter = new ArrayAdapter <string>(this, R.Layouts.device_name); // Find and set up the ListView for paired devices var pairedListView = (ListView)FindViewById(R.Ids.paired_devices); pairedListView.Adapter = mPairedDevicesArrayAdapter; pairedListView.ItemClick += OnDeviceClick; // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView)FindViewById(R.Ids.new_devices); newDevicesListView.Adapter = mNewDevicesArrayAdapter; newDevicesListView.ItemClick += OnDeviceClick; // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.RegisterReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.RegisterReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.GetDefaultAdapter(); // Get a set of currently paired devices var pairedDevices = mBtAdapter.BondedDevices; // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.Size() > 0) { FindViewById(R.Ids.title_paired_devices).Visibility = View.VISIBLE; foreach (BluetoothDevice device in pairedDevices.AsEnumerable()) { mPairedDevicesArrayAdapter.Add(device.Name + "\n" + device.Address); } } else { string noDevices = GetResources().GetText(R.Strings.none_paired).ToString(); mPairedDevicesArrayAdapter.Add(noDevices); } }
public string seqId;//取样编号 #endregion #region 创建Activity protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.YugaSamp); username = Intent.GetStringExtra("username"); //厂家 samp_factory = FindViewById <EditText>(Resource.Id.sampFactory); samp_factory.Text = "豫港"; //数据库查询地点 //bsif.selectAdress( out bsif.sampAdress, out bsif.adressCode); samp_adress = FindViewById <EditText>(Resource.Id.sampAdress); samp_adress.Text = "豫港焦炭皮带称"; adressID = 11; adressCode = "11"; //货物名称 samp_goodsname = FindViewById <EditText>(Resource.Id.sampGoodsname); cNCGoodsCode = "0700000602"; samp_goodsname.Text = "焦炭"; //业务类型 //业务类型下拉菜单 sp_mode = FindViewById <Spinner>(Resource.Id.sampMode); sp_mode.ItemSelected += selectMode_ItemSelected; //数据库查询 暂不用 //bsif.sampModeNameList = bsif.selectSampMode(); //填充xml数据 ArrayAdapter adapter_mode = ArrayAdapter.CreateFromResource(this, Resource.Array.SampMode, Android.Resource.Layout.SimpleSpinnerItem); adapter_mode.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); sp_mode.Adapter = adapter_mode; sp_mode.Prompt = "请选择"; ////填充数据 数据库数据 //ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, bsif.sampModeNameList); //adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //sp_mode.Adapter = adapter; //日期 string tmnw = System.DateTime.Now.ToString("yyyy-MM-dd HH:ss:mm"); samp_time = FindViewById <EditText>(Resource.Id.sampTime); samp_time.Text = tmnw; //取样人 samp_people = FindViewById <EditText>(Resource.Id.sampPeople); samp_people.Text = username; btSamp = FindViewById <ToggleButton>(Resource.Id.btSamp); btSamp.Enabled = false; btSamp.SetBackgroundColor(Android.Graphics.Color.ParseColor("#e6e6e6")); btSamp.Click += OperateDialogBox; if (CommonFunction.mode == "NFC") { #region NFC 模式 try { m_nfcAdapter = NfcAdapter.GetDefaultAdapter(this); if (m_nfcAdapter == null) { CommonFunction.ShowMessage("设备不支持NFC!", this, true); return; } if (!m_nfcAdapter.IsEnabled) { CommonFunction.ShowMessage("请在系统设置中先启用NFC功能!", this, true); return; } //m_nfcAdapter.SetNdefPushMessage(CreateNdefMessageCallback(), this, this); mTechLists = new string[][] { new string[] { "Android.Nfc.Tech.MifareClassic" }, new string[] { "Android.Nfc.Tech.NfcA" } }; IntentFilter tech = new IntentFilter(NfcAdapter.ActionTechDiscovered); mFilters = new IntentFilter[] { tech, }; //存放支持technologies的数组 mPendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(YugaSamp)).AddFlags(ActivityFlags.SingleTop), PendingIntentFlags.UpdateCurrent); //intent过滤器,过滤类型为NDEF_DISCOVERED //Mifare卡和Desfare卡都是ISO - 14443 - A卡 ProcessAdapterAction(this.Intent); } catch (Exception ex) { CommonFunction.ShowMessage(ex.Message, this, true); } #endregion } else if (CommonFunction.mode == "SerialPort") { #region SerialPort模式 try { Stream im; Stream om; serial = new SerialPort(13, 115200, 0); serial.Power_5Von(); im = serial.MFileInputStream; om = serial.MFileOutputStream; hf = new HfReader(im, om); } catch (Exception ex) { CommonFunction.ShowMessage(ex.Message, this, true); } #endregion } }
protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.Window.RequestFeature(WindowFeatures.ActionBar); base.OnCreate(bundle); mContext = this; Instance = this; try { var width = Resources.DisplayMetrics.WidthPixels; var height = Resources.DisplayMetrics.HeightPixels; var density = Resources.DisplayMetrics.Density; //屏幕密度 App.ScreenWidth = width / density; //屏幕宽度 App.ScreenHeight = height / density; //屏幕高度 } catch (System.Exception) { } //返回此活动是否为任务的根 if (!IsTaskRoot) { Finish(); return; } PowerManager pm = (PowerManager)GetSystemService(Context.PowerService); isPause = pm.IsScreenOn; if (handler == null) { handler = new Handler(); } //注册广播,屏幕点亮状态监听,用于单独控制音乐播放 if (screenStateReceiver == null) { screenStateReceiver = new ScreenStateReceiver(); var intentFilter = new IntentFilter(); intentFilter.AddAction("_ACTION_SCREEN_OFF"); //熄屏 intentFilter.AddAction("_ACTION_SCREEN_ON"); //点亮 intentFilter.AddAction("_ACTION_BACKGROUND"); //后台 intentFilter.AddAction("_ACTION_FOREGROUND"); //前台 RegisterReceiver(screenStateReceiver, intentFilter); } Window.AddFlags(WindowManagerFlags.KeepScreenOn); if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { Window.ClearFlags(WindowManagerFlags.TranslucentStatus); Window.AddFlags(WindowManagerFlags.TranslucentNavigation); TranslucentStatubar.Immersive(Window); Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds); Window.ClearFlags(WindowManagerFlags.Fullscreen); } //在andrioid m之后,必须在运行时请求权限 GetPersimmions(); //图片裁切 BitImageEditor.Droid.Platform.Init(this, bundle); //初始 Popup Popup.Init(this); //版本更新配置 AutoUpdate.Init(this, "com.dcms.clientv3.fileprovider"); //初始 Xamarin.Forms 实验性标志 Forms.SetFlags("Shell_Experimental", "SwipeView_Experimental", "CarouselView_Experimental", "RadioButton_Experimental", "IndicatorView_Experimental", "Expander_Experimental", "Visual_Experimental", "CollectionView_Experimental", "FastRenderers_Experimental"); #region //初始 FFImageLoading CachedImageRenderer.Init(true); CachedImageRenderer.InitImageViewHandler(); ImageCircleRenderer.Init(); var config = new FFImageLoading.Config.Configuration() { VerboseLogging = false, VerbosePerformanceLogging = false, VerboseMemoryCacheLogging = false, VerboseLoadingCancelledLogging = false, }; ImageService.Instance.Initialize(config); #endregion Forms.Init(this, bundle); //初始 对话框组件 UserDialogs.Init(this); //初始 ZXing ZXingPlatform.Platform.Init(); LoadApplication(new App(new AndroidInitializer())); }
public override void AddObserver(string eventName, IEventObserver observer) { IntentFilter intent = new IntentFilter(eventName); LocalBroadcastManager.GetInstance(context).RegisterReceiver((EventObserver)observer, intent); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Kp2aLog.Log("Received intent to provide access to entry"); _stopOnLockBroadcastReceiver = new StopOnLockBroadcastReceiver(this); IntentFilter filter = new IntentFilter(); filter.AddAction(Intents.DatabaseLocked); RegisterReceiver(_stopOnLockBroadcastReceiver, filter); if ((intent.Action == Intents.ShowNotification) || (intent.Action == Intents.UpdateKeyboard)) { String entryId = intent.GetStringExtra(EntryActivity.KeyEntry); String searchUrl = intent.GetStringExtra(SearchUrlTask.UrlToSearchKey); if (entryId == null) { Kp2aLog.Log("received intent " + intent.Action + " without KeyEntry!"); #if DEBUG throw new Exception("invalid intent received!"); #endif return(StartCommandResult.NotSticky); } PwEntryOutput entry; try { ElementAndDatabaseId fullId = new ElementAndDatabaseId(entryId); if (((App.Kp2a.LastOpenedEntry != null) && (fullId.ElementId.Equals(App.Kp2a.LastOpenedEntry.Uuid)))) { entry = App.Kp2a.LastOpenedEntry; } else { Database entryDb = App.Kp2a.GetDatabase(fullId.DatabaseId); entry = new PwEntryOutput(entryDb.EntriesById[fullId.ElementId], entryDb); } } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); //seems like restarting the service happened after closing the DB StopSelf(); return(StartCommandResult.NotSticky); } if (intent.Action == Intents.ShowNotification) { //first time opening the entry -> bring up the notifications bool activateKeyboard = intent.GetBooleanExtra(EntryActivity.KeyActivateKeyboard, false); DisplayAccessNotifications(entry, activateKeyboard, searchUrl); } else //UpdateKeyboard { #if !EXCLUDE_KEYBOARD //this action is received when the data in the entry has changed (e.g. by plugins) //update the keyboard data. //Check if keyboard is (still) available if (Keepass2android.Kbbridge.KeyboardData.EntryId == entry.Uuid.ToHexString()) { MakeAccessibleForKeyboard(entry, searchUrl); } #endif } } if (intent.Action == Intents.CopyStringToClipboard) { TimeoutCopyToClipboard(intent.GetStringExtra(_stringtocopy)); } if (intent.Action == Intents.ActivateKeyboard) { ActivateKp2aKeyboard(); } if (intent.Action == Intents.ClearNotificationsAndData) { ClearNotifications(); } return(StartCommandResult.RedeliverIntent); }
// inspired by http://baroqueworksdev.blogspot.com/2012/09/how-to-handle-screen-onoff-and-keygurad.html protected override void onCreate(global::android.os.Bundle savedInstanceState) { base.onCreate(savedInstanceState); var sv = new ScrollView(this); var ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); this.setContentView(sv); new Button(this).WithText("register").AttachTo(ll).AtClick( btn => { btn.setEnabled(false); // get KeyGuardManager var mKeyguard = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); var mReceiver = new MyBroadcastReceiver(); mReceiver.AtReceive += (Context context, Intent intent) => { #region Notify int counter = 0; Action <string> Notify = Title => { counter++; var nm = (NotificationManager)this.getSystemService(Activity.NOTIFICATION_SERVICE); // see http://developer.android.com/reference/android/app/Notification.html var notification = new Notification( android.R.drawable.star_on, Title, java.lang.System.currentTimeMillis() ); // ToClass is like GetTypeInfo var notificationIntent = new Intent(this, typeof(AndroidUnlockActivity).ToClass()); var contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo( this, Title, "", contentIntent); // http://stackoverflow.com/questions/10402686/how-to-have-led-light-notification notification.defaults |= Notification.DEFAULT_VIBRATE; notification.defaults |= Notification.DEFAULT_SOUND; //notification.defaults |= Notification.DEFAULT_LIGHTS; notification.defaults |= Notification.FLAG_SHOW_LIGHTS; // http://androiddrawableexplorer.appspot.com/ nm.notify(counter, notification); //context.ToNotification( // Title: Title, // Content: Title, // id: (int)java.lang.System.currentTimeMillis(), // icon: android.R.drawable.star_on, // uri: "http://my.jsc-solutions.net" // ); }; #endregion var action = intent.getAction(); if (action == Intent.ACTION_SCREEN_OFF) { // Screen is off Notify("ACTION_SCREEN_OFF"); } else if (action == Intent.ACTION_SCREEN_ON) { // Intent.ACTION_USER_PRESENT will be broadcast when the screen // is // unlocked. // if API Level 16 /* * if(mKeyguard.isKeyguardLocked()){ // the keyguard is * currently locked. Log.e("","ACTION_SCREEN_ON : locked"); } */ if (mKeyguard.inKeyguardRestrictedInputMode()) { // the keyguard is currently locked. Notify("ACTION_SCREEN_ON : locked"); } else { // unlocked Notify("ACTION_SCREEN_ON : unlocked"); } } else if (action == Intent.ACTION_USER_PRESENT) { // The user has unlocked the screen. Enabled! Notify("ACTION_USER_PRESENT"); } }; // IntetFilter with Action IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(Intent.ACTION_SCREEN_ON); intentFilter.addAction(Intent.ACTION_USER_PRESENT); // Keyguard is GONE // register BroadcastReceiver and IntentFilter registerReceiver(mReceiver, intentFilter); } ); //this.ShowToast("http://jsc-solutions.net"); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.RandomSamp); LoginSystemType = Intent.GetStringExtra("LoginSystemType"); username = Intent.GetStringExtra("username"); //摇号抽样按钮 btExtra = FindViewById <ToggleButton>(Resource.Id.btExtract); btExtra.Click += extractSamp; btExtra.Enabled = false; btExtra.SetBackgroundColor(Android.Graphics.Color.ParseColor("#E6E6E6")); //不摇号取样按钮 btNoExtra = FindViewById <ToggleButton>(Resource.Id.btNoExtra); btNoExtra.Click += noExtraSamp; btNoExtra.Enabled = true; btNoExtra.SetBackgroundColor(Android.Graphics.Color.ParseColor("#BD2B32")); //计量通行证号 cmeasure_Id = FindViewById <EditText>(Resource.Id.cMeasureId); //地点 samp_adress = FindViewById <EditText>(Resource.Id.sampAdress); samp_adress.Text = "合金库"; //供应商 samp_factory = FindViewById <EditText>(Resource.Id.sampFactory); //存货名称 samp_goodsname = FindViewById <EditText>(Resource.Id.sampGoodsname); //车号 samp_carNumber = FindViewById <EditText>(Resource.Id.sampCarNum); //取样包数 samp_bags = FindViewById <EditText>(Resource.Id.bagCount); //抽取包数 extra_bags = FindViewById <EditText>(Resource.Id.extractBags); //业务类型下拉菜单 sp_mode = FindViewById <Spinner>(Resource.Id.sampMode); //填充数据 sp_mode.ItemSelected += selectMode_ItemSelected; //数据库查询 暂时不用 //bsif.sampModeNameList = bsif.selectSampMode(); //填充数据 数据库数据 //ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, bsif.sampModeNameList); //adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //sp_mode.Adapter = adapter; //填充xml文件数据 ArrayAdapter adapter_mode = ArrayAdapter.CreateFromResource(this, Resource.Array.SampMode, Android.Resource.Layout.SimpleSpinnerItem); adapter_mode.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); sp_mode.Adapter = adapter_mode; sp_mode.Prompt = "请选择"; //取样包数文本框改变事件 //editText没有焦点 samp_bags.TextChanged += TextChange; if (CommonFunction.mode == "NFC") { #region NFC 模式 try { m_nfcAdapter = NfcAdapter.GetDefaultAdapter(this); if (m_nfcAdapter == null) { CommonFunction.ShowMessage("设备不支持NFC!", this, true); return; } if (!m_nfcAdapter.IsEnabled) { CommonFunction.ShowMessage("请在系统设置中先启用NFC功能!", this, true); return; } //m_nfcAdapter.SetNdefPushMessage(CreateNdefMessageCallback(), this, this); mTechLists = new string[][] { new string[] { "Android.Nfc.Tech.MifareClassic" }, new string[] { "Android.Nfc.Tech.NfcA" } }; IntentFilter tech = new IntentFilter(NfcAdapter.ActionTechDiscovered); mFilters = new IntentFilter[] { tech, }; //存放支持technologies的数组 mPendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(RandomClass)).AddFlags(ActivityFlags.SingleTop), PendingIntentFlags.UpdateCurrent); //intent过滤器,过滤类型为NDEF_DISCOVERED //Mifare卡和Desfare卡都是ISO - 14443 - A卡 ProcessAdapterAction(this.Intent); } catch (Exception ex) { CommonFunction.ShowMessage(ex.Message, this, true); } #endregion } else if (CommonFunction.mode == "SerialPort") { #region SerialPort模式 try { Stream im; Stream om; serial = new SerialPort(13, 115200, 0); serial.Power_5Von(); im = serial.MFileInputStream; om = serial.MFileOutputStream; hf = new HfReader(im, om); } catch (Exception ex) { CommonFunction.ShowMessage(ex.Message, this, true); } #endregion } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.Unload); UserName = Intent.GetStringExtra("username"); bunload = FindViewById <ToggleButton>(Resource.Id.buUnLoad); bunload.Enabled = false; bunload.Click += OperateDialogBox; bhalfreturn = FindViewById <ToggleButton>(Resource.Id.buHalfReturn); bhalfreturn.Enabled = false; bhalfreturn.Click += OperateDialogBox; ballreturn = FindViewById <ToggleButton>(Resource.Id.buAllReturn); ballreturn.Enabled = false; ballreturn.Click += OperateDialogBox; bunloadandload = FindViewById <ToggleButton>(Resource.Id.buUnloadAndLoad); bunloadandload.Enabled = false; bunloadandload.Click += OperateDialogBox; UserName = Intent.GetStringExtra("username"); EditText person = FindViewById <EditText>(Resource.Id.tuPerson); person.Text = UserName; EditText buckleweight = FindViewById <EditText>(Resource.Id.eBuckleWeight); buckleweight.TextChanged += Buckleweight_TextChanged; if (CommonFunction.mode == "NFC") { #region NFC 模式 try { m_nfcAdapter = NfcAdapter.GetDefaultAdapter(this); if (m_nfcAdapter == null) { CommonFunction.ShowMessage("设备不支持NFC!", this, true); return; } if (!m_nfcAdapter.IsEnabled) { CommonFunction.ShowMessage("请在系统设置中先启用NFC功能!", this, true); return; } //m_nfcAdapter.SetNdefPushMessage(CreateNdefMessageCallback(), this, this); mTechLists = new string[][] { new string[] { "Android.Nfc.Tech.MifareClassic" }, new string[] { "Android.Nfc.Tech.NfcA" } }; IntentFilter tech = new IntentFilter(NfcAdapter.ActionTechDiscovered); mFilters = new IntentFilter[] { tech, }; //存放支持technologies的数组 mPendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(Unload)).AddFlags(ActivityFlags.SingleTop), PendingIntentFlags.UpdateCurrent); //intent过滤器,过滤类型为NDEF_DISCOVERED //Mifare卡和Desfare卡都是ISO - 14443 - A卡 ProcessAdapterAction(this.Intent); } catch (Exception ex) { CommonFunction.ShowMessage(ex.Message, this, true); } #endregion } else if (CommonFunction.mode == "SerialPort") { #region SerialPort模式 try { Stream im; Stream om; serial = new SerialPort(13, 115200, 0); serial.Power_5Von(); im = serial.MFileInputStream; om = serial.MFileOutputStream; hf = new HfReader(im, om); } catch (Exception ex) { CommonFunction.ShowMessage(ex.Message, this, true); } #endregion } }
/// <summary> /// Registers the receiver using <see cref="Application.Context"/>. /// </summary> /// <returns>The receiver intent.</returns> /// <param name="receiver">Receiver.</param> /// <param name="intentFilter">Intent filter.</param> public static Intent RegisterReceiver(this BroadcastReceiver receiver, IntentFilter intentFilter) { return(Application.Context.RegisterReceiver(receiver, intentFilter)); }
//public IObservable<Configuration> WhenConfigurationChanged() => this // .WhenIntentReceived(Intent.ActionConfigurationChanged) // .Select(intent => this.AppContext.Resources.Configuration); //public PendingIntent GetIntentServicePendingIntent() //{ // var intent = new Intent(Application.Context, typeof(CoreIntentService)); // var pendingIntent = PendingIntent.GetService(this.AppContext, 0, intent, PendingIntentFlags.UpdateCurrent); // return pendingIntent; //} public T GetIntentValue <T>(string intentAction, Func <Intent, T> transform) { using (var filter = new IntentFilter(intentAction)) using (var receiver = this.AppContext.RegisterReceiver(null, filter)) return(transform(receiver)); }
public void OnReceived(IDictionary <string, string> parameters) { System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived"); if (parameters.ContainsKey(SilentKey) && (parameters[SilentKey] == "true" || parameters[SilentKey] == "1")) { return; } Context context = Android.App.Application.Context; int notifyId = 0; string title = context.ApplicationInfo.LoadLabel(context.PackageManager); string message = ""; string tag = ""; if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTextKey) && parameters.ContainsKey(FirebasePushNotificationManager.NotificationContentTextKey)) { message = parameters[FirebasePushNotificationManager.NotificationContentTextKey].ToString(); } else if (parameters.ContainsKey(AlertKey)) { message = $"{parameters[AlertKey]}"; } else if (parameters.ContainsKey(BodyKey)) { message = $"{parameters[BodyKey]}"; } else if (parameters.ContainsKey(MessageKey)) { message = $"{parameters[MessageKey]}"; } else if (parameters.ContainsKey(SubtitleKey)) { message = $"{parameters[SubtitleKey]}"; } else if (parameters.ContainsKey(TextKey)) { message = $"{parameters[TextKey]}"; } if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTitleKey) && parameters.ContainsKey(FirebasePushNotificationManager.NotificationContentTitleKey)) { title = parameters[FirebasePushNotificationManager.NotificationContentTitleKey].ToString(); } else if (parameters.ContainsKey(TitleKey)) { if (!string.IsNullOrEmpty(message)) { title = $"{parameters[TitleKey]}"; } else { message = $"{parameters[TitleKey]}"; } } if (parameters.ContainsKey(IdKey)) { var str = parameters[IdKey].ToString(); try { notifyId = Convert.ToInt32(str); } catch (System.Exception ex) { // Keep the default value of zero for the notify_id, but log the conversion problem. System.Diagnostics.Debug.WriteLine("Failed to convert {0} to an integer", str); } } if (parameters.ContainsKey(TagKey)) { tag = parameters[TagKey].ToString(); } if (FirebasePushNotificationManager.SoundUri == null) { FirebasePushNotificationManager.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); } try { if (FirebasePushNotificationManager.IconResource == 0) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; } else { string name = context.Resources.GetResourceName(FirebasePushNotificationManager.IconResource); if (name == null) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; } } } catch (Android.Content.Res.Resources.NotFoundException ex) { FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon; System.Diagnostics.Debug.WriteLine(ex.ToString()); } Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName); //Intent resultIntent = new Intent(context, typeof(T)); Bundle extras = new Bundle(); foreach (var p in parameters) { extras.PutString(p.Key, p.Value); } if (extras != null) { extras.PutInt(ActionNotificationIdKey, notifyId); extras.PutString(ActionNotificationTagKey, tag); resultIntent.PutExtras(extras); } resultIntent.SetFlags(ActivityFlags.ClearTop); var pendingIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); var notificationBuilder = new NotificationCompat.Builder(context) .SetSmallIcon(FirebasePushNotificationManager.IconResource) .SetContentTitle(title) .SetSound(FirebasePushNotificationManager.SoundUri) .SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) .SetContentText(message) .SetAutoCancel(true) .SetContentIntent(pendingIntent); if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean) { // Using BigText notification style to support long message var style = new NotificationCompat.BigTextStyle(); style.BigText(message); notificationBuilder.SetStyle(style); } string category = string.Empty; if (parameters.ContainsKey(CategoryKey)) { category = parameters[CategoryKey]; } if (parameters.ContainsKey(ActionKey)) { category = parameters[ActionKey]; } var notificationCategories = CrossFirebasePushNotification.Current?.GetUserNotificationCategories(); if (notificationCategories != null && notificationCategories.Length > 0) { IntentFilter intentFilter = null; foreach (var userCat in notificationCategories) { if (userCat != null && userCat.Actions != null && userCat.Actions.Count > 0) { foreach (var action in userCat.Actions) { if (userCat.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase)) { Intent actionIntent = null; PendingIntent pendingActionIntent = null; if (action.Type == NotificationActionType.Foreground) { actionIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName); actionIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); actionIntent.SetAction($"{action.Id}"); extras.PutString(ActionIdentifierKey, action.Id); actionIntent.PutExtras(extras); pendingActionIntent = PendingIntent.GetActivity(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); } else { actionIntent = new Intent(); //actionIntent.SetAction($"{category}.{action.Id}"); actionIntent.SetAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}"); extras.PutString(ActionIdentifierKey, action.Id); actionIntent.PutExtras(extras); pendingActionIntent = PendingIntent.GetBroadcast(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); } notificationBuilder.AddAction(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent); } if (FirebasePushNotificationManager.ActionReceiver == null) { if (intentFilter == null) { intentFilter = new IntentFilter(); } if (!intentFilter.HasAction(action.Id)) { intentFilter.AddAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}"); } } } } } if (intentFilter != null) { FirebasePushNotificationManager.ActionReceiver = new PushNotificationActionReceiver(); context.RegisterReceiver(FirebasePushNotificationManager.ActionReceiver, intentFilter); } } NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); notificationManager.Notify(tag, notifyId, notificationBuilder.Build()); }