def register(self, intentName, actionName, callback): self.br = BroadcastReceiver(self.on_broadcast, actions=[intentName + actionName]) self.intentName = intentName self.actionName = actionName self.callback = callback self.registered = True
def build(self): self.title = "Bluetooth Input Reader" self.theme_cls.primary_palette = "Pink" self.theme_cls.primary_hue = "400" self.icon = '/res/images/poolleaf_16619.png' self.use_kivy_settings = False self.br = None self.br_strt = False if platform == 'android': self.br = BroadcastReceiver(self.on_broadcast, actions=['state_changed'])
def __init__(self, config): Analyzer.__init__(self) self.__log_dir = util.get_mobileinsight_log_path() self.__dec_log_dir = util.get_mobileinsight_log_decoded_path() self.__orig_file = "" self.__raw_msg = {} self.__raw_msg_key = "" self.__msg_cnt = 0 self.__dec_msg = [] self.__is_wifi_enabled = False self.__log_timestamp = "" self.__upload_log_flag = True try: if config['privacy'] == '1': self.__upload_log_flag = True else: self.__upload_log_flag = False except BaseException: self.__upload_log_flag = False try: if config['is_use_wifi'] == '1': self.__is_use_wifi = True else: self.__is_use_wifi = False except BaseException: self.__is_use_wifi = False try: if config['is_dec_log'] == '1': self.__is_dec_log = True self.__dec_log_name = "diag_log_" + \ datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + ".txt" self.__dec_log_path = os.path.join(self.__dec_log_dir, self.__dec_log_name) else: self.__is_dec_log = False except BaseException: self.__is_dec_log = False try: self.__dec_log_type = config['log_type'] except BaseException: self.__dec_log_type = "" if not os.path.exists(self.__log_dir): os.makedirs(self.__log_dir) if not os.path.exists(self.__dec_log_dir): os.makedirs(self.__dec_log_dir) self.add_source_callback(self._logger_filter) self.br = BroadcastReceiver(self.on_broadcast, actions=['MobileInsight.Main.StopService']) self.br.start()
async def pair(self, *args, **kwargs) -> bool: """Pair with the peripheral. You can use ConnectDevice method if you already know the MAC address of the device. Else you need to StartDiscovery, Trust, Pair and Connect in sequence. Returns: Boolean regarding success of pairing. """ loop = asyncio.get_event_loop() bondedFuture = loop.create_future() def handleBondStateChanged(context, intent): bond_state = intent.getIntExtra( defs.BluetoothDevice.EXTRA_BOND_STATE, -1) if bond_state == -1: loop.call_soon_threadsafe( bondedFuture.set_exception, BleakError(f"Unexpected bond state {bond_state}"), ) elif bond_state == defs.BluetoothDevice.BOND_NONE: loop.call_soon_threadsafe( bondedFuture.set_exception, BleakError( f"Device with address {self.address} could not be paired with." ), ) elif bond_state == defs.BluetoothDevice.BOND_BONDED: loop.call_soon_threadsafe(bondedFuture.set_result, True) receiver = BroadcastReceiver( handleBondStateChanged, actions=[defs.BluetoothDevice.ACTION_BOND_STATE_CHANGED], ) receiver.start() try: # See if it is already paired. bond_state = self.__device.getBondState() if bond_state == defs.BluetoothDevice.BOND_BONDED: return True elif bond_state == defs.BluetoothDevice.BOND_NONE: logger.debug(f"Pairing to BLE device @ {self.address}") if not self.__device.createBond(): raise BleakError( f"Could not initiate bonding with device @ {self.address}" ) return await bondedFuture finally: await receiver.stop()
def __init__(self, request_handler, gevent_queue, config, logger): self.config = config self.request_handler = request_handler self.action = self.config["listenActions"] self.logger = logger self.logger.info("!!!listening on action " + self.action) self.issuer = self.config["Issuer"], self.logger.info("!!!listening on action " + self.action) self.allowedIssuers = self.config["Issuer"].split(',') self.logger.info("!!!listening on action " + self.action) if gevent_queue is not None: self.gevent_queue = gevent_queue else: self.gevent_queue = None self.logger.info("starting the broadcast receiver") self.br = BroadcastReceiver(self._handle_intent_request, actions=[self.action]) self.list_iter = PythonListIterator() self.m2m_service_callback = M2MServiceCallbackImpl(None) self.m2mservice_binder = M2MServiceBinder() self.logger.info("created the callback") M2MServiceBinder.setCallback(self.m2m_service_callback) PythonService.setBinder(self.m2mservice_binder) context = PythonService.mService # service = M2MService() # service.onCreate() # service.onStartCommand(None, 0, 0) # service.setContext(context) serviceIntent = Intent() #serviceIntent.setClassName("org.openmtc.m2mservice", "org.openmtc.m2mservice.M2MService"); serviceIntent.setClassName("org.renpy.android", "org.renpy.android.PythonService") #serviceIntent.setClassName("com.example.test_bind_service_server2", "com.example.test_bind_service_server2.DemoService"); #context = PythonActivity.mActivity ok = context.bindService(serviceIntent) if ok is False: print("python could not start m2mservice") else: print("python starting component " + ok) self.logger.info("set the callback")
def __init__(self, config, logger, api): super(AndroidWiFiManager, self).__init__(config, logger, api) self.general_android_conn = GeneralAndroidConnectivity( self.logger, self.api) self.wifi_android_controller = WiFiAndroidController( self.logger, self.general_android_conn) self.context = PythonService.mService self.wifi_manager = self.context.getSystemService(Context.WIFI_SERVICE) self.conn_manager = self.context.getSystemService( Context.CONNECTIVITY_SERVICE) self.conn_change_br = BroadcastReceiver( self.handle_conn_change_alert, actions=[ConnectivityManager.CONNECTIVITY_ACTION]) self.addConnectionAlert( self.general_android_conn.updateConnectivityMgmtObj)
def notify(self, title, message): global service if not self.check_notification_timeout(): return self._last_notification_time = datetime.now() icon = getattr(Drawable, 'icon') noti = NotificationBuilder(service) noti.setPriority( Notification.PRIORITY_MAX ) # //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads noti.Up Display Style noti.setDefaults( Notification.DEFAULT_ALL ) # //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style noti.setContentTitle(AndroidString((title).encode('utf-8'))) noti.setContentText(AndroidString((message).encode('utf-8'))) noti.setTicker(AndroidString(('Appix').encode('utf-8'))) noti.setSmallIcon(icon) noti.setAutoCancel(True) id = 996543 appintent = Intent(Intent.ACTION_PROVIDER_CHANGED) pi_app = PendingIntent.getBroadcast(service, id, appintent, PendingIntent.FLAG_UPDATE_CURRENT) appintent.setData(Uri.parse('close')) # closeintent = Intent(Intent.ACTION_RUN) # pi_close = PendingIntent.getBroadcast(service, id, closeintent, PendingIntent.FLAG_UPDATE_CURRENT) # closeintent.setData(Uri.parse('open')) if not hasattr(self, 'br'): self.br = BroadcastReceiver(self.on_broadcast, actions=['provider_changed', 'run']) self.br.start() noti.addAction(0, AndroidString("Launch App"), pi_app) # noti.addAction(0, AndroidString("Close Service"), pi_close) if SDK_INT >= 16: noti = noti.build() else: noti = noti.getNotification() _ns.notify(0, noti)
def schedule_alarms(alarmas): Logger.debug("%s: schedule_alarms %s" % (APP, datetime.now())) from jnius import autoclass from android.broadcast import BroadcastReceiver SystemClock = autoclass('android.os.SystemClock') AlarmManager = autoclass('android.app.AlarmManager') global broadcast_receiver broadcast_receiver = BroadcastReceiver(process_broadcast, [ 'org.jtc.planilla.SERVICEALARM', Intent.ACTION_USER_PRESENT, 'org.jtc.planilla.APP_AWAKE' ]) broadcast_receiver.start() am = activity.getSystemService(Context.ALARM_SERVICE) # Cancelar todas las posibles alarmas que hubiera de un servicio anterior intent = Intent(String('org.jtc.planilla.SERVICEALARM')) for i in range(20): # Suponemos que no hay más de 20 alarmas! pi = PendingIntent.getBroadcast(activity, i, intent, 0) am.cancel(pi) # Fijar las nuevas alarmas i = 0 now = datetime.now() for id, alarma in alarmas.iteritems(): intent = Intent(String('org.jtc.planilla.SERVICEALARM')).putExtra( "id", id) pi = PendingIntent.getBroadcast(activity, i, intent, PendingIntent.FLAG_UPDATE_CURRENT) ms = (alarma['hora'] - now).seconds * 1000 Logger.debug("%s: Hora: %s - En %s" % (APP, alarma['hora'], tdformat(alarma['hora'] - now))) am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + ms, pi) i += 1
def __init__(self, config): Analyzer.__init__(self) self.__log_dir = util.get_mobileinsight_log_path() self.__dec_log_dir = util.get_mobileinsight_log_decoded_path() self.__orig_file = "" self.__raw_msg = {} self.__raw_msg_key = "" self.__msg_cnt = 0 self.__dec_msg = [] self.__is_wifi_enabled = False self.state = states[0] self.sr_round = 0 self.round = 0 self.sr_record = [] self.record = { 'round': 0, 'total': 0, 'msg': [], } self.__sr_log_path = "%s/sr/sr_latency_%s_%s_%s.txt" % \ (util.get_mobileinsight_path(), datetime.now().strftime('%Y%m%d_%H%M%S'), util.get_phone_info(), util.get_operator_info()) self.__MILabPluginName = 'SRLatency' self.__own_log_uploaded_dir = os.path.join( util.get_mobileinsight_plugin_path(), self.__MILabPluginName, "log", "uploaded") if not os.path.exists(self.__own_log_uploaded_dir): os.makedirs(self.__own_log_uploaded_dir) self.__task = "Unknown" if 'task' in config: self.__task = config['task'] self.__own_log_task_dir = os.path.join( util.get_mobileinsight_plugin_path(), self.__MILabPluginName, "log", self.__task) if not os.path.exists(self.__own_log_task_dir): os.makedirs(self.__own_log_task_dir) try: if config['is_use_wifi'] == '1': self.__is_use_wifi = True else: self.__is_use_wifi = False except BaseException: self.__is_use_wifi = False # try: # if config['is_dec_log'] == '1': # self.__is_dec_log = True # self.__dec_log_name = "diag_log_" + \ # datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + ".txt" # self.__dec_log_path = os.path.join( # self.__dec_log_dir, self.__dec_log_name) # else: # self.__is_dec_log = False # except BaseException: # self.__is_dec_log = False try: self.__dec_log_type = config['log_type'] except BaseException: self.__dec_log_type = "" if not os.path.exists(self.__log_dir): os.makedirs(self.__log_dir) if not os.path.exists(self.__dec_log_dir): os.makedirs(self.__dec_log_dir) self.add_source_callback(self._logger_filter) # Add this code at the end of onCreate() self.br = BroadcastReceiver(self.on_broadcast, actions=['MobileInsight.Main.StopService']) self.br.start()
def registerBroadcastReceivers(self): self.brStopAck = BroadcastReceiver(self.on_broadcastStopServiceAck, actions=['MobileInsight.Plugin.StopServiceAck']) self.brStopAck.start()
def __init__(self, **kwargs): self.debug_params = dict() self.addit_params = dict() for key, val in kwargs.items(): mo = re.search('^debug_([^_]+)_(.+)', key) if mo: kk = mo.group(1) ll = self.debug_params.get(kk, dict()) ll[mo.group(2)] = val self.debug_params[kk] = ll elif key.startswith('ab_'): self.addit_params[key[3:]] = val else: setattr(self, key, val) _LOGGER.debug( f'Addit params for DM {self.addit_params} AND {self.debug_params}') self.db = None self.oscer = None self.notification_formatter_info = dict() self.connectors_format = False self.devicemanager_class_by_type = dict() self.devicemanagers_pre_actions = dict() self.devicemanagers_by_id = dict() self.devicemanagers_by_uid = dict() self.connectors_info = [] self.users = [] self.views = [] self.devices = [] self.devicemanagers_active = [] self.devicemanagers_active_done = [] self.timer_obj = None self.main_session = None self.last_user = None self.devicemanagers_active_info = dict() self.stop_event = asyncio.Event() self.last_notify_ms = time() * 1000 if self.android: from jnius import autoclass from android.broadcast import BroadcastReceiver self.Context = autoclass('android.content.Context') self.AndroidString = autoclass('java.lang.String') self.NotificationCompatInboxStyle = autoclass( 'android.app.Notification$InboxStyle') NotificationBuilder = autoclass('android.app.Notification$Builder') self.PythonActivity = autoclass('org.kivy.android.PythonActivity') self.service = autoclass('org.kivy.android.PythonService').mService NOTIFICATION_CHANNEL_ID = self.AndroidString( self.service.getPackageName().encode('utf-8')) self.NOTIFICATION_GROUP = 'pyMovizGroup' self.FOREGROUND_NOTIFICATION_ID = 4563 app_context = self.service.getApplication().getApplicationContext() self.app_context = app_context self.notification_service = self.service.getSystemService( self.Context.NOTIFICATION_SERVICE) self.CONNECT_ACTION = 'device_manager_service.view.CONNECT' self.DISCONNECT_ACTION = 'device_manager_service.view.DISCONNECT' self.STOP_ACTION = 'device_manager_service.STOP' self.br = BroadcastReceiver(self.on_broadcast, actions=[ self.CONNECT_ACTION, PRESENCE_REQUEST_ACTION, self.DISCONNECT_ACTION, self.STOP_ACTION ]) self.br.start() Intent = autoclass('android.content.Intent') self.Intent = Intent PendingIntent = autoclass('android.app.PendingIntent') NotificationActionBuilder = autoclass( 'android.app.Notification$Action$Builder') Notification = autoclass('android.app.Notification') Color = autoclass("android.graphics.Color") NotificationChannel = autoclass('android.app.NotificationChannel') NotificationManager = autoclass('android.app.NotificationManager') channelName = self.AndroidString( 'DeviceManagerService'.encode('utf-8')) chan = NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT) chan.setLightColor(Color.BLUE) chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE) self.notification_service.createNotificationChannel(chan) BitmapFactory = autoclass("android.graphics.BitmapFactory") Icon = autoclass("android.graphics.drawable.Icon") BitmapFactoryOptions = autoclass( "android.graphics.BitmapFactory$Options") # Drawable = jnius.autoclass("{}.R$drawable".format(service.getPackageName())) # icon = getattr(Drawable, 'icon') options = BitmapFactoryOptions() # options.inMutable = True # declaredField = options.getClass().getDeclaredField("inPreferredConfig") # declaredField.set(cast('java.lang.Object',options), cast('java.lang.Object', BitmapConfig.ARGB_8888)) # options.inPreferredConfig = BitmapConfig.ARGB_8888; notification_image = join(dirname(__file__), '..', 'images', 'device_manager.png') bm = BitmapFactory.decodeFile(notification_image, options) notification_icon = Icon.createWithBitmap(bm) notification_image = join(dirname(__file__), '..', 'images', 'lan-connect.png') bm = BitmapFactory.decodeFile(notification_image, options) icon = Icon.createWithBitmap(bm) broadcastIntent = Intent(self.CONNECT_ACTION) actionIntent = PendingIntent.getBroadcast( self.service, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT) connect_action = NotificationActionBuilder( icon, self.AndroidString('CONNECT'.encode('utf-8')), actionIntent).build() notification_image = join(dirname(__file__), '..', 'images', 'lan-disconnect.png') bm = BitmapFactory.decodeFile(notification_image, options) icon = Icon.createWithBitmap(bm) broadcastIntent = Intent(self.DISCONNECT_ACTION) actionIntent = PendingIntent.getBroadcast( self.service, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT) disconnect_action = NotificationActionBuilder( icon, self.AndroidString('DISCONNECT'.encode('utf-8')), actionIntent).build() notification_image = join(dirname(__file__), '..', 'images', 'stop.png') bm = BitmapFactory.decodeFile(notification_image, options) icon = Icon.createWithBitmap(bm) broadcastIntent = Intent(self.STOP_ACTION) actionIntent = PendingIntent.getBroadcast( self.service, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT) stop_action = NotificationActionBuilder( icon, self.AndroidString('STOP'.encode('utf-8')), actionIntent).build() notification_intent = Intent(app_context, self.PythonActivity) notification_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK) notification_intent.setAction(Intent.ACTION_MAIN) notification_intent.addCategory(Intent.CATEGORY_LAUNCHER) notification_intent = PendingIntent.getActivity( self.service, 0, notification_intent, 0) self.notification_builder = NotificationBuilder(app_context, NOTIFICATION_CHANNEL_ID)\ .setContentIntent(notification_intent)\ .setSmallIcon(notification_icon)\ .addAction(connect_action)\ .addAction(disconnect_action)\ .addAction(stop_action) self.notification_builder_no_action = NotificationBuilder(app_context, NOTIFICATION_CHANNEL_ID)\ .setContentIntent(notification_intent)\ .setSmallIcon(notification_icon)
def on_resume(self): self.br = BroadcastReceiver(self.on_broadcast, actions=['state_changed']) self.start_broadcats() return True
# I don't remember if I need this or not but I'm too lazy # to get my phone out and redeploy to test right now sms_manager = autoclass("android.telephony.SmsManager") sms_manager.getDefault() def on_sms_received(context, intent): # Bundle up the intent extras msg_bundle = Bundle(intent.getExtras()) # Pull out all the pdus pdus = [m for m in msg_bundle.get("pdus")] # This next line used to do a thing, but doesn't any more. # I guess I should take it out msg_bytes = [p for p in pdus] # Reconstruct the message messages = [SmsMessage.createFromPdu(mb) for mb in msg_bytes] for m in messages: print m.getMessageBody() # Define the type of action we want to react to SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED" # Register a call back for that action in a BR br = BroadcastReceiver(on_sms_received, actions=[SMS_RECEIVED]) # Start the reveiver listening br.start() # Keep the service alive while 1: time.sleep(60 * 5)
def register_broadcats_receiver(self): if not self.br: self.br = BroadcastReceiver( self.on_broadcast, actions=['SCAN_RESULTS_AVAILABLE_ACTION']) self.br.start()