예제 #1
1
    def _choose_image(self, on_complete, filename=None):
        assert(on_complete is not None)
        self.on_complete = on_complete
        self.filename = filename

        activity.unbind(on_activity_result=self.on_activity_result)
        activity.bind(on_activity_result=self.on_activity_result)
        intent = Intent(Intent.ACTION_PICK)
        intent.setType("image/jpeg")
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, True)
        #intent.putExtra(Intent.EXTRA_LOCAL_ONLY, True)
        #intent.putExtra(Intent.CATEGORY_OPENABLE, True)
        PythonActivity.mActivity.startActivityForResult(
            Intent.createChooser(intent, autoclass(
                'java.lang.String')("Select Picture")), 0x100)
예제 #2
1
        def onConnectionFailed(self, connectionResult):
            Logger.info(
                "Google: connection failed. Error code: %s. Trying to resolve..." % connectionResult.getErrorCode())

            if self.in_resolving_connection:
                Logger.info("Google: already in resolving, pass...")
                return

            self.in_resolving_connection = True

            if connectionResult.hasResolution():
                Logger.info("Google: starting resolution...")
                activity.bind(on_activity_result=self.on_activity_result)
                connectionResult.startResolutionForResult(PythonActivity.mActivity, self.RC_RESOLUTION)
            else:
                Logger.info("Google: connection issue has no resolution... "
                            "hasResolution says: %s" % connectionResult.hasResolution())
예제 #3
0
    def on_start(self):
        """ This is the start point of the kivy ui
        """
        import time

        Logger.info("Time to on_start: {} <<<<<<<<".format(time.clock()))
        win = Window
        win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
        win.bind(on_key_down=self.on_key_down)
        win.softinput_mode = "below_target"
        self.on_size(win, win.size)
        self.init_ui()
        self.load_wallet_by_name(self.electrum_config.get_wallet_path())
        # init plugins
        run_hook("init_kivy", self)
        # default tab
        self.switch_to("history")
        # bind intent for bitcoin: URI scheme
        if platform == "android":
            from android import activity
            from jnius import autoclass

            PythonActivity = autoclass("org.renpy.android.PythonActivity")
            mactivity = PythonActivity.mActivity
            self.on_new_intent(mactivity.getIntent())
            activity.bind(on_new_intent=self.on_new_intent)

        # URI passed in config
        uri = self.electrum_config.get("url")
        if uri:
            self.set_URI(uri)
예제 #4
0
파일: filechooser.py 프로젝트: kivy/plyer
    def _open_file(self, **kwargs):
        '''
        Running Android Activity is non-blocking and the only call
        that blocks is onActivityResult running in GUI thread

        .. versionadded:: 1.4.0
        '''

        # set up selection handler
        # startActivityForResult is async
        # onActivityResult is sync
        self._handle_selection = kwargs.pop(
            'on_selection', self._handle_selection
        )

        # create Intent for opening
        file_intent = Intent(Intent.ACTION_GET_CONTENT)
        file_intent.setType('*/*')
        file_intent.addCategory(
            Intent.CATEGORY_OPENABLE
        )

        # bind a function for a response from filechooser activity
        activity.bind(on_activity_result=self._on_activity_result)

        # start a new activity from PythonActivity
        # which creates a filechooser via intent
        mActivity.startActivityForResult(
            Intent.createChooser(file_intent, cast(
                'java.lang.CharSequence',
                String("FileChooser")
            )),
            self.select_code
        )
예제 #5
0
    def on_start(self):
        Logger.debug("%s: on_start %s" % (APP, datetime.now()))

        from kivy.core.window import Window
        Window.bind(on_keyboard=self.on_keypress)

        if platform == 'android':
            android.map_key(android.KEYCODE_BACK, 1001)

            import android.activity as python_activity
            python_activity.bind(on_new_intent=self.on_new_intent)
            self.on_new_intent(activity.getIntent())

        self.server_url = self.config.get('general', 'server_url')

        self.root.bind(
            on_touch_down=lambda *a: setattr(self, 'delay_image_loading', True),
            on_touch_up=lambda *a: setattr(self, 'delay_image_loading', False))

        imagedir = ImageDir(server_url=self.server_url)
        wp = 'with_previous'
        imagedir.bind(
            on_navigate_top=lambda *a: setattr(self.root, wp, False),
            on_navigate_down=lambda *a: setattr(self.root, wp, True),
            on_img_selected=self.load_carousel,
            path=lambda w,v: setattr(self.root, 'title', v),
            on_loading_start=lambda *a: setattr(self.root, 'loading', True),
            on_loading_stop=lambda *a: setattr(self.root, 'loading', False))
        self.imagedir = imagedir

        self.root.container.add_widget(imagedir)
        self.root.bind(on_touch_down=lambda *a: Loader.pause(),
                       on_touch_up=lambda *a: Loader.resume())
        Loader.max_upload_per_frame = 1  # Maximize interactivity
예제 #6
0
    def on_start(self):
        ''' This is the start point of the kivy ui
        '''
        import time
        Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
        win = Window
        win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
        win.bind(on_key_down=self.on_key_down)
        #win.softinput_mode = 'below_target'
        self.on_size(win, win.size)
        self.init_ui()
        self.load_wallet_by_name(self.electrum_config.get_wallet_path())
        # init plugins
        run_hook('init_kivy', self)

        # fiat currency
        self.fiat_unit = self.fx.ccy if self.fx.is_enabled() else ''
        self.network.register_callback(self.on_quotes, ['on_quotes'])
        self.network.register_callback(self.on_history, ['on_history'])

        # default tab
        self.switch_to('history')
        # bind intent for bitcoin: URI scheme
        if platform == 'android':
            from android import activity
            from jnius import autoclass
            PythonActivity = autoclass('org.kivy.android.PythonActivity')
            mactivity = PythonActivity.mActivity
            self.on_new_intent(mactivity.getIntent())
            activity.bind(on_new_intent=self.on_new_intent)

        # URI passed in config
        uri = self.electrum_config.get('url')
        if uri:
            self.set_URI(uri)
예제 #7
0
    def on_start(self):
        ''' This is the start point of the kivy ui
        '''
        import time
        Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
        Logger.info("dpi: {} {}".format(metrics.dpi, metrics.dpi_rounded))
        win = Window
        win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
        win.bind(on_key_down=self.on_key_down)
        win.softinput_mode = 'below_target'
        self.on_size(win, win.size)
        self.init_ui()
        self.load_wallet_by_name(self.electrum_config.get_wallet_path())
        # init plugins
        run_hook('init_kivy', self)
        # default tab
        self.switch_to('history')
        # bind intent for bitcoin: URI scheme
        if platform == 'android':
            from android import activity
            from jnius import autoclass
            PythonActivity = autoclass('org.renpy.android.PythonActivity')
            mactivity = PythonActivity.mActivity
            self.on_new_intent(mactivity.getIntent())
            activity.bind(on_new_intent=self.on_new_intent)

        # URI passed in config
        uri = self.electrum_config.get('url')
        if uri:
            self.set_URI(uri)
예제 #8
0
def user_select_image(callback):
    """Open Gallery Activity and call callback with absolute image filepath of image user selected.
    None if user canceled.
    """

    # PythonActivity.mActivity is the instance of the current Activity
    # BUT, startActivity is a method from the Activity class, not from our
    # PythonActivity.
    # We need to cast our class into an activity and use it
    currentActivity = cast('android.app.Activity', PythonActivity.mActivity)

    # Forum discussion: https://groups.google.com/forum/#!msg/kivy-users/bjsG2j9bptI/-Oe_aGo0newJ
    def on_activity_result(request_code, result_code, intent):
        if request_code != RESULT_LOAD_IMAGE:
            Logger.warning('user_select_image: ignoring activity result that was not RESULT_LOAD_IMAGE')
            return

        try:
            if result_code == Activity.RESULT_CANCELED:
                Clock.schedule_once(lambda dt: callback(None), 0)
                return

            if result_code != Activity.RESULT_OK:
                # This may just go into the void...
                raise NotImplementedError('Unknown result_code "{}"'.format(result_code))

            selectedImage = intent.getData()  # Uri
            filePathColumn = [MediaStore_Images_Media_DATA] # String[]
            # Cursor
            cursor = currentActivity.getContentResolver().query(selectedImage,
                    filePathColumn, None, None, None)
            cursor.moveToFirst()

            # int
            columnIndex = cursor.getColumnIndex(filePathColumn[0])
            # String
            picturePath = cursor.getString(columnIndex)
            cursor.close()
            Logger.info('android_ui: user_select_image() selected %s', picturePath)

            # This is possibly in a different thread?
            Clock.schedule_once(lambda dt: callback(picturePath), 0)

        finally:
            activity.unbind(on_activity_result=on_activity_result)

    # See: http://pyjnius.readthedocs.org/en/latest/android.html
    activity.bind(on_activity_result=on_activity_result)

    intent = Intent()

    # http://programmerguru.com/android-tutorial/how-to-pick-image-from-gallery/
    # http://stackoverflow.com/questions/18416122/open-gallery-app-in-android
    intent.setAction(Intent.ACTION_PICK)
    # TODO internal vs external?
    intent.setData(Uri.parse('content://media/internal/images/media'))
    # TODO setType(Image)?

    currentActivity.startActivityForResult(intent, RESULT_LOAD_IMAGE)
예제 #9
0
 def __init__(self, credentials, toasty=True):
     self.credentials = credentials
     self._auth_state = None
     self._processing = False
     self._awaiting_resume=False
     self.toasty = toasty
     # bind to catch callback from browser
     activity.bind(on_new_intent=self._webview_intent_callback)
     App.get_running_app().bind(on_resume=self._check_resume)
예제 #10
0
 def _setup_finished(self, result):
     if result.isSuccess():
         Logger.info('Setup complete. Scheduling inventory check!')
         self.setup_complete = True
         a = App.get_running_app()
         a.bind(on_stop=self._dispose)
         activity.bind(on_activity_result=self._on_activity_result) 
         self._get_inventory()
     else:
         Logger.info('There was a problem with setup...')
    def __init__(self, app_id, permissions=['basic_info'], toasty=True):
        super(AndroidFacebook, self).__init__()
        self._app_id = app_id
        self._permissions = permissions
        self.toasty = toasty
        self._pending_request = None

        activity.bind(on_activity_result=self._on_activity_result)
        self._session_callback = _FacebookStatusCallback(self)
        self._session = None
예제 #12
0
def start_scanning(callback):
    global INTENT_LOCK
    if not ADAPTER.isEnabled() and not INTENT_LOCK:
        print "binding activity result"
        activity.bind(on_activity_result=activity_result)
        INTENT_LOCK = True
        print "starting activity for result"
        SERVICE.startActivityForResult(
            Intent(BTAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT)
    else:
        ADAPTER.startLeScan(callback)
예제 #13
0
 def _setup_callback(self, result):
     if result.isSuccess() and self.helper.mSetupDone:
         Logger.info('Setup complete. Scheduling inventory check')
         self.setup_complete = True
         a = App.get_running_app()
         a.bind(on_stop=self._dispose)
         activity.bind(on_activity_result=self._on_activity_result)
         self._get_inventory()
     else:
         Logger.info('There was a problem with setup')
         self.error_msg = 'could not connect to play store'
         self._fail()
예제 #14
0
 def scan_qr(self, on_complete):
     from jnius import autoclass
     from android import activity
     PythonActivity = autoclass('org.renpy.android.PythonActivity')
     Intent = autoclass('android.content.Intent')
     intent = Intent("com.google.zxing.client.android.SCAN")
     intent.putExtra("SCAN_MODE", "QR_CODE_MODE")
     def on_qr_result(requestCode, resultCode, intent):
         if requestCode == 0:
             if resultCode == -1: # RESULT_OK:
                 contents = intent.getStringExtra("SCAN_RESULT")
                 if intent.getStringExtra("SCAN_RESULT_FORMAT") == 'QR_CODE':
                     on_complete(contents)
     activity.bind(on_activity_result=on_qr_result)
     PythonActivity.mActivity.startActivityForResult(intent, 0)
예제 #15
0
 def scan_qr_zxing(self, on_complete):
     # uses zxing embedded lib
     if platform != 'android':
         return
     from jnius import autoclass
     from android import activity
     PythonActivity = autoclass('org.renpy.android.PythonActivity')
     IntentIntegrator = autoclass('com.google.zxing.integration.android.IntentIntegrator')
     integrator = IntentIntegrator(PythonActivity.mActivity)
     def on_qr_result(requestCode, resultCode, intent):
         if requestCode == 0:
             if resultCode == -1: # RESULT_OK:
                 contents = intent.getStringExtra("SCAN_RESULT")
                 if intent.getStringExtra("SCAN_RESULT_FORMAT") == 'QR_CODE':
                     on_complete(contents)
                 else:
                     self.show_error("wrong format " + intent.getStringExtra("SCAN_RESULT_FORMAT"))
     activity.bind(on_activity_result=on_qr_result)
     integrator.initiateScan()
예제 #16
0
    def scan_qr(self, on_complete):
        if platform != 'android':
            return
        from jnius import autoclass, cast
        from android import activity
        PythonActivity = autoclass('org.kivy.android.PythonActivity')
        SimpleScannerActivity = autoclass("org.electrum.qr.SimpleScannerActivity")
        Intent = autoclass('android.content.Intent')
        intent = Intent(PythonActivity.mActivity, SimpleScannerActivity)

        def on_qr_result(requestCode, resultCode, intent):
            if resultCode == -1:  # RESULT_OK:
                #  this doesn't work due to some bug in jnius:
                # contents = intent.getStringExtra("text")
                String = autoclass("java.lang.String")
                contents = intent.getStringExtra(String("text"))
                on_complete(contents)
        activity.bind(on_activity_result=on_qr_result)
        PythonActivity.mActivity.startActivityForResult(intent, 0)
예제 #17
0
 def on_start(self):
     ''' This is the start point of the kivy ui
     '''
     import time
     Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
     win = Window
     win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
     win.bind(on_key_down=self.on_key_down)
     #win.softinput_mode = 'below_target'
     self.on_size(win, win.size)
     self.init_ui()
     crash_reporter.ExceptionHook(self)
     # init plugins
     run_hook('init_kivy', self)
     # fiat currency
     self.fiat_unit = self.fx.ccy if self.fx.is_enabled() else ''
     # default tab
     self.switch_to('history')
     # bind intent for dash: URI scheme
     if platform == 'android':
         from android import activity
         from jnius import autoclass
         PythonActivity = autoclass('org.kivy.android.PythonActivity')
         mactivity = PythonActivity.mActivity
         self.on_new_intent(mactivity.getIntent())
         activity.bind(on_new_intent=self.on_new_intent)
     # connect callbacks
     if self.network:
         interests = ['updated', 'status', 'new_transaction', 'verified', 'interfaces']
         self.network.register_callback(self.on_network_event, interests)
         self.network.register_callback(self.on_fee, ['fee'])
         self.network.register_callback(self.on_fee_histogram, ['fee_histogram'])
         self.network.register_callback(self.on_quotes, ['on_quotes'])
         self.network.register_callback(self.on_history, ['on_history'])
         if self.network.tor_auto_on and not self.network.tor_on:
             self.show_tor_warning()
     # load wallet
     self.load_wallet_by_name(self.electrum_config.get_wallet_path())
     # URI passed in config
     uri = self.electrum_config.get('url')
     if uri:
         self.set_URI(uri)
예제 #18
0
    def on_start(self):
        Config.set('kivy', 'log_level',
                   self.config.get('general', 'log_level'))
        Logger.debug("%s: on_start %s" % (APP, datetime.now()))

        self.scmgr = self.root.scmgr  # scmgr identificado con id en el kv

        if self.config.get('general', 'nucleo') not in ('Ruta', 'TMA'):
            self.pedir_nucleo()

        numero = int(self.config.get('general', 'numero'))
        try:
            planilla = self.config.get('general', 'planilla')
        except:
            planilla = ""  # failsafe
        try:
            final = datetime.strptime(
                self.config.get('general', 'final'), "%d/%m/%y %H:%M")
        except Exception:
            final = None
        Logger.debug("Final %s" % final)
        if numero != 0 and final and final > datetime.now() and planilla != "":
            # 0 indica que no estamos rearrancando
            # Evita que cambiar s1 y s2 arranque el servicio
            self.restarting = True
            self.asigna_numero(planilla, numero)
        else:
            self.toast(u"Escoge tu número de planilla")

        from kivy.core.window import Window
        Window.bind(on_keyboard=self.on_keypress)

        if platform == 'android':
            android.map_key(android.KEYCODE_BACK, 1001)

            import android.activity as python_activity
            python_activity.bind(on_new_intent=self.on_new_intent)
            # on_new_intent sólo se llama cuando la aplicación ya está
            # arrancada. Para no duplicar código la llamamos desde aquí
            self.on_new_intent(activity.getIntent())

        self.restarting = False
예제 #19
0
 def scan_qr(self, on_complete):
     from jnius import autoclass
     from android import activity
     PythonActivity = autoclass('org.renpy.android.PythonActivity')
     Intent = autoclass('android.content.Intent')
     intent = Intent("com.google.zxing.client.android.SCAN")
     intent.putExtra("SCAN_MODE", "QR_CODE_MODE")
     def on_qr_result(requestCode, resultCode, intent):
         if requestCode == 0:
             if resultCode == -1: # RESULT_OK:
                 contents = intent.getStringExtra("SCAN_RESULT")
                 if intent.getStringExtra("SCAN_RESULT_FORMAT") == 'QR_CODE':
                     try:
                         uri = electrum.util.parse_URI(contents)
                     except:
                         self.show_info("Invalid URI", url)
                         return
                     on_complete(uri)
     activity.bind(on_activity_result=on_qr_result)
     PythonActivity.mActivity.startActivityForResult(intent, 0)
예제 #20
0
    def nfc_init(self):
        ''' This is where we initialize NFC adapter.
        '''
        # Initialize NFC
        global app
        app = App.get_running_app()

        # Make sure we are listening to new intent 
        activity.bind(on_new_intent=self.on_new_intent)

        # Configure nfc
        self.j_context = context = PythonActivity.mActivity
        self.nfc_adapter = NfcAdapter.getDefaultAdapter(context)
        # Check if adapter exists
        if not self.nfc_adapter:
            return False
        
        # specify that we want our activity to remain on top whan a new intent
        # is fired
        self.nfc_pending_intent = PendingIntent.getActivity(context, 0,
            Intent(context, context.getClass()).addFlags(
                Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)

        # Filter for different types of action, by default we enable all.
        # These are only for handling different NFC technologies when app is in foreground
        self.ndef_detected = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        #self.tech_detected = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
        #self.tag_detected = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)

        # setup tag discovery for ourt tag type
        try:
            self.ndef_detected.addCategory(Intent.CATEGORY_DEFAULT)
            # setup the foreground dispatch to detect all mime types
            self.ndef_detected.addDataType('*/*')

            self.ndef_exchange_filters = [self.ndef_detected]
        except Exception as err:
            raise Exception(repr(err))
        return True
예제 #21
0
    def scan_qr(self, on_complete):
        if platform != 'android':
            return
        from jnius import autoclass, cast
        from android import activity
        PythonActivity = autoclass('org.kivy.android.PythonActivity')
        SimpleScannerActivity = autoclass("org.electrum.qr.SimpleScannerActivity")
        Intent = autoclass('android.content.Intent')
        intent = Intent(PythonActivity.mActivity, SimpleScannerActivity)

        def on_qr_result(requestCode, resultCode, intent):
            try:
                if resultCode == -1:  # RESULT_OK:
                    #  this doesn't work due to some bug in jnius:
                    # contents = intent.getStringExtra("text")
                    String = autoclass("java.lang.String")
                    contents = intent.getStringExtra(String("text"))
                    on_complete(contents)
            finally:
                activity.unbind(on_activity_result=on_qr_result)
        activity.bind(on_activity_result=on_qr_result)
        PythonActivity.mActivity.startActivityForResult(intent, 0)
예제 #22
0
 def scan_qr(self, on_complete):
     if platform != 'android':
         return
     from jnius import autoclass
     from android import activity
     PythonActivity = autoclass('org.kivy.android.PythonActivity')
     Intent = autoclass('android.content.Intent')
     intent = Intent("com.google.zxing.client.android.SCAN")
     intent.putExtra("SCAN_MODE", "QR_CODE_MODE")
     def on_qr_result(requestCode, resultCode, intent):
         if requestCode == 0:
             if resultCode == -1: # RESULT_OK:
                 contents = intent.getStringExtra("SCAN_RESULT")
                 if intent.getStringExtra("SCAN_RESULT_FORMAT") == 'QR_CODE':
                     on_complete(contents)
                 else:
                     self.show_error("wrong format " + intent.getStringExtra("SCAN_RESULT_FORMAT"))
     activity.bind(on_activity_result=on_qr_result)
     try:
         PythonActivity.mActivity.startActivityForResult(intent, 0)
     except:
         self.show_error(_('Could not start Barcode Scanner.') + ' ' + _('Please install the Barcode Scanner app from ZXing'))
예제 #23
0
    def nfc_init(self):
        ''' This is where we initialize NFC adapter.
        '''
        # Initialize NFC
        global app
        app = App.get_running_app()

        # Make sure we are listening to new intent 
        activity.bind(on_new_intent=self.on_new_intent)

        # Configure nfc
        self.j_context = context = PythonActivity.mActivity
        self.nfc_adapter = NfcAdapter.getDefaultAdapter(context)
        # Check if adapter exists
        if not self.nfc_adapter:
            return False
        
        # specify that we want our activity to remain on top when a new intent
        # is fired
        self.nfc_pending_intent = PendingIntent.getActivity(context, 0,
            Intent(context, context.getClass()).addFlags(
                Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)

        # Filter for different types of action, by default we enable all.
        # These are only for handling different NFC technologies when app is in foreground
        self.ndef_detected = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        #self.tech_detected = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
        #self.tag_detected = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)

        # setup tag discovery for ourt tag type
        try:
            self.ndef_detected.addCategory(Intent.CATEGORY_DEFAULT)
            # setup the foreground dispatch to detect all mime types
            self.ndef_detected.addDataType('*/*')

            self.ndef_exchange_filters = [self.ndef_detected]
        except Exception as err:
            raise Exception(repr(err))
        return True
 def on_start(self):
     ''' This is the start point of the kivy ui
     '''
     import time
     Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
     win = Window
     win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
     win.bind(on_key_down=self.on_key_down)
     #win.softinput_mode = 'below_target'
     self.on_size(win, win.size)
     self.init_ui()
     self.load_wallet_by_name(self.electrum_config.get_wallet_path())
     # init plugins
     run_hook('init_kivy', self)
     # fiat currency
     self.fiat_unit = self.fx.ccy if self.fx.is_enabled() else ''
     # default tab
     self.switch_to('history')
     # bind intent for bitcoin: URI scheme
     if platform == 'android':
         from android import activity
         from jnius import autoclass
         PythonActivity = autoclass('org.kivy.android.PythonActivity')
         mactivity = PythonActivity.mActivity
         self.on_new_intent(mactivity.getIntent())
         activity.bind(on_new_intent=self.on_new_intent)
     # connect callbacks
     if self.network:
         interests = [
             'updated', 'status', 'new_transaction', 'verified',
             'interfaces'
         ]
         self.network.register_callback(self.on_network_event, interests)
         self.network.register_callback(self.on_quotes, ['on_quotes'])
         self.network.register_callback(self.on_history, ['on_history'])
     # URI passed in config
     uri = self.electrum_config.get('url')
     if uri:
         self.set_URI(uri)
예제 #25
0
    def buy(self, sku, callbacks=None):
        import uuid

        Intent = autoclass('android.content.Intent')
        try:
            super(AndroidBillingService, self).buy(sku, callbacks)
        except BillingException:
            return

        if not self.service:
            return
        self.developer_payload = str(uuid.uuid4())
        buy_intent_bundle = self.service.getBuyIntent(
            3, self.python_activity.getPackageName(), sku,
            settings.INAPP_PURCHASES[sku]['type'], self.developer_payload)
        response = buy_intent_bundle.getInt("BILLING_RESPONSE_RESULT_OK")
        if response == 0:
            Logger.info("Android Billing: buy response OK")
            pending_intent = buy_intent_bundle.getParcelable("BUY_INTENT")
            if not pending_intent:
                return
            from jnius import cast

            pending_intent = cast('android.app.PendingIntent', pending_intent)
            # noinspection PyUnresolvedReferences
            from android import activity

            activity.bind(on_activity_result=self.on_activity_result)
            sender = pending_intent.getIntentSender()
            self.python_activity.startIntentSenderForResult(
                sender, self.RC_BILLING, Intent(), 0, 0, 0)
            if self._purchased_items:
                self._purchased_items = []
        else:
            Logger.warning(
                "Android Billing: buy attempt code is not OK, but %s" %
                response)
예제 #26
0
파일: camera.py 프로젝트: Guhan2211/plyer
    def take_picture(self, on_complete):

        self.on_complete = on_complete

        camera_intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        photo_file = self._create_image_file()

        if photo_file is not None:
            
            photo_uri = FileProvider.getUriForFile(
                self.currentActivity.getApplicationContext(),
                self.currentActivity.getApplicationContext().getPackageName(),
                photo_file
            )
            
            parcelable = cast('android.os.Parcelable', photo_uri)
            
            activity.unbind(on_activity_result=self.on_activity_result)
            activity.bind(on_activity_result=self.on_activity_result)

            camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable)
           
            self.currentActivity.startActivityForResult(camera_intent, self.CAMERA_REQUEST_CODE)
예제 #27
0
파일: pushyy.py 프로젝트: Fox520/pushyy
    def notification_click_handler(self, callback: Callable[[RemoteMessage], None]):
        """Function to call when push notification is clicked

        Example
        def my_click_callback(data: RemoteMessage):
            print(data)

        Parameters:
        callback (function): Callback function reference

        Returns:
        None

        """
        self.__notification_click_callback = callback

        # gg https://github.com/spesmilo/electrum/blob/6650e6bbae12a79e12667857ee039f1b1f30c7e3/electrum/gui/kivy/main_window.py#L620
        from android import activity

        PythonActivity = autoclass("org.kivy.android.PythonActivity")
        mactivity = PythonActivity.mActivity
        # Bind to when application appears on the foreground
        self.__on_new_intent(mactivity.getIntent())
        activity.bind(on_new_intent=self.__on_new_intent)
예제 #28
0
파일: main.py 프로젝트: johtso/noGo
    def build(self):
        print 'ENTERED BUILD()'
        t1 = time()
        # Load config
        #print 'user data dir is', self.user_data_dir
        config = self.config
        #print 'my config is',config

        sound = SoundLoader.load('./media/sounds/stone_sound5.mp3')
        sound.volume = 0.05
        self.stone_sound = sound

        # Get any json collection backups if on android
        if platform() == 'android':
            if not exists('/sdcard/noGo'):
                mkdir('/sdcard/noGo')
            if not exists('/sdcard/noGo/collections'):
                mkdir('/sdcard/noGo/collections')
            if not exists('/sdcard/noGo/collections/unsaved'):
                mkdir('/sdcard/noGo/collections/unsaved')
            json_backups = glob('/sdcard/noGo/*.json')
            for filen in json_backups:
                with open(filen,'r') as fileh:
                    filestr = fileh.read()
                if len(filestr) > 1:
                    name = filen.split('/')[-1]
                    copyfile(filen,'./collections/'+name)
           

        # Load collections
        # self.collections = CollectionsList().from_file()
        #self.build_collections_list()

        
        # Construct GUI
        sm = NogoManager(transition=SlideTransition(direction='left'))
        self.manager = sm
        sm.app = self

        # hv = Screen(name="Home")
        # hs = HomeScreen(managedby=sm)
        # hv.add_widget(hs)
        # sm.add_widget(hv)
        # sm.create_collections_index()

        t2 = time()
        print 'CONSTRUCTED manager and home',t2-t1

        # Get initial settings from config panel
        config = self.config
        sm.propagate_input_mode(config.getdefault('Board','input_mode','phone'))
        sm.propagate_coordinates_mode(config.getdefault('Board','coordinates','1'))
        self.stone_type = config.getdefault('Board','stone_graphics','simple')
        self.boardtype = config.getdefault('Board','board_graphics','simple')
        sm.propagate_boardtype_mode(self.boardtype)
        sm.propagate_view_mode(config.getdefault('Board','view_mode','phone'))
        self.set_sounds(config.getdefault('Board','sounds','0'))

        # Rebuild homescreen *after* setting phone/tablet mode
        #sm.add_widget(Screen(name='emptyscreen'))
        sm.rebuild_homescreen()
        sm.current = 'Home'


        self.bind(on_start=self.post_build_init)

        if platform() == 'android':
            from android import activity
            activity.bind(on_new_intent=self.on_intent)

            self.PythonActivity = autoclass('org.renpy.android.PythonActivity')
            self.ActivityInfo = autoclass('android.content.pm.ActivityInfo')
            
            

        t3 = time()
        print 'RETURNING SM',t3-t2, t3-t1

        #drawer = NogoDrawer()
        #drawer.add_widget(NavigationButtons())
        #drawer.add_widget(Image(source='media/logo_big2.png',
        #                        allow_stretch=True,
        #                        mipmap=True))
        #drawer.add_widget(sm)

        #self.navdrawer = drawer

        #return drawer
        
        return sm
예제 #29
0
    def user_select_image(self):
        """Open Gallery Activity and call callback with absolute image filepath of image user selected.
        None if user canceled.
        """

        # PythonActivity.mActivity is the instance of the current Activity
        # BUT, startActivity is a method from the Activity class, not from our
        # PythonActivity.
        # We need to cast our class into an activity and use it
        currentActivity = cast('android.app.Activity',
                               PythonActivity.mActivity)

        # Forum discussion: https://groups.google.com/forum/#!msg/kivy-users/bjsG2j9bptI/-Oe_aGo0newJ
        def on_activity_result(request_code, result_code, intent):
            if request_code != RESULT_LOAD_IMAGE:
                Logger.warning(
                    'user_select_image: ignoring activity result that was not RESULT_LOAD_IMAGE'
                )
                return

            if result_code == Activity.RESULT_CANCELED:
                # Clock.schedule_once(lambda dt: callback(None), 0)

                activity.unbind(on_activity_result=on_activity_result)
                return

            if result_code != Activity.RESULT_OK:
                # This may just go into the void...
                raise NotImplementedError(
                    'Unknown result_code "{}"'.format(result_code))

            selectedImage = intent.getData()
            # Uri
            filePathColumn = [MediaStore_Images_Media_DATA]
            # String[]
            # Cursor
            cursor = currentActivity.getContentResolver().query(
                selectedImage, filePathColumn, None, None, None)
            cursor.moveToFirst()

            # int
            columnIndex = cursor.getColumnIndex(filePathColumn[0])
            # String
            picturePath = cursor.getString(columnIndex)
            cursor.close()
            Logger.info('android_ui: user_select_image() selected %s',
                        picturePath)

            # This is possibly in a different thread?
            # Clock.schedule_once(lambda dt: callback(picturePath), 0)

            print(picturePath)
            Gambler.path_of_picture = picturePath

            activity.unbind(on_activity_result=on_activity_result)
            from main import update
            update.picture = Gambler.path_of_picture

        # See: http://pyjnius.readthedocs.org/en/latest/android.html
        activity.bind(on_activity_result=on_activity_result)

        intent = Intent()

        # http://programmerguru.com/android-tutorial/how-to-pick-image-from-gallery/
        # http://stackoverflow.com/questions/18416122/open-gallery-app-in-android
        intent.setAction(Intent.ACTION_PICK)
        # TODO internal vs external?
        intent.setData(Uri.parse('content://media/internal/images/media'))
        # TODO setType(Image)?

        currentActivity.startActivityForResult(intent, RESULT_LOAD_IMAGE)

        return True
예제 #30
0
 def choose_gallery(self):
     self._popup.dismiss()
     activity.bind(on_activity_result=self._on_activity_result)
     picker = Intent(Intent.ACTION_PICK)
     picker.setType('image/*')
     PythonActivity.mActivity.startActivityForResult(picker, 0x100)
예제 #31
0
	def __init__(self):
		if is_android():
			## reflect our activity with the main apps activity
			self.current_activity = cast("android.app.Activity", PythonActivity.mActivity)
			## tell android where to send our speech results
			activity.bind(on_activity_result=self.on_activity_result)
예제 #32
0
 def __init__(self, folder_path):
     activity.bind(on_activity_result=self.on_activity_result)
     self.folder_path = folder_path
     self.shot_taken = BooleanProperty(False)
예제 #33
0
def nfc_enable(self):
    activity.bind(on_new_intent=self.on_new_intent)
예제 #34
0
 def __init__(self, text_callback=None, video_callback=None):
     self.text_callback = text_callback
     self.video_callback = video_callback
     self.intent = mActivity.getIntent()
     self.intent_handler(self.intent)
     activity.bind(on_new_intent=self.intent_handler)
예제 #35
0
파일: main.py 프로젝트: Dernaksi/kivy
 def build(self):
     self.index = 0
     activity.bind(on_activity_result=self.on_activity_result)
예제 #36
0
def uri_to_file(uri):
    cursor = Activity.getContentResolver().query(uri, None, None, None, None)
    column_index = cursor.getColumnIndexOrThrow("_data")
    if cursor.moveToFirst():
        return cursor.getString(column_index)


UriToFile = uri_to_file


def ActivityResults(requestCode, resultCode, intent):
    for method in on_results_methods:
        method(requestCode, resultCode, intent)


activity.bind(on_activity_result=ActivityResults)


def PhoneCall_(number):
    _intent = Intent(Intent.ACTION_VIEW, Uri.parse('tel:' + str(number)))
    Activity.startActivity(_intent)


def PhoneCall(number):
    phoneIntent = Intent(Intent.ACTION_CALL)
    phoneIntent.setData(Uri.parse("tel:" + str(number)))
    Activity.startActivity(phoneIntent)


def ViewContact(contact_id):
    intent = Intent(Intent.ACTION_VIEW)
예제 #37
0
파일: main.py 프로젝트: brousch/playground
 def choose_gallery(self):
     self._popup.dismiss()
     activity.bind(on_activity_result=self._on_activity_result)
     picker = Intent(Intent.ACTION_PICK)
     picker.setType('image/*')
     PythonActivity.mActivity.startActivityForResult(picker, 0x100)
예제 #38
0
파일: dispatcher.py 프로젝트: andmart/able
 def _set_ble_interface(self):
     self._events_interface = PythonBluetooth(self)
     self._ble = BLE(self._events_interface)
     activity.bind(on_activity_result=self.on_activity_result)
예제 #39
0
 def _set_ble_interface(self):
     self._events_interface = PythonBluetooth(self)
     self._ble = BLE(self._events_interface)
     if not self._is_service_context:
         activity.bind(on_activity_result=self.on_activity_result)
예제 #40
0
파일: main.py 프로젝트: PHPDOTSQL/kivy
 def build(self):
     self.index = 0
     activity.bind(on_activity_result=self.on_activity_result)
예제 #41
0
파일: main.py 프로젝트: brousch/playground
 def nfc_enable(self):
     print 'nfc_enable()'
     activity.bind(on_new_intent=self.on_new_intent)
예제 #42
0
 def __init__(self, callback=None, **kwargs):
     self.REQUEST_CODE = 42
     self.callback = callback
     activity.bind(on_activity_result=self.intent_callback)
예제 #43
0
파일: main.py 프로젝트: pombredanne/noGo
    def build(self):
        print 'ENTERED BUILD()'
        t1 = time()
        # Load config
        #print 'user data dir is', self.user_data_dir
        config = self.config
        #print 'my config is', config

        def load_sound(*args):
            sound = SoundLoader.load('./media/sounds/stone_sound5.mp3')
            sound.volume = 0.05
            self.stone_sound = sound
        Clock.schedule_once(load_sound, 1)

        # Get any json collection backups if on android
        if platform() == 'android':
            if not exists('/sdcard/noGo'):
                mkdir('/sdcard/noGo')
            if not exists('/sdcard/noGo/collections'):
                mkdir('/sdcard/noGo/collections')
            if not exists('/sdcard/noGo/collections/unsaved'):
                mkdir('/sdcard/noGo/collections/unsaved')
            json_backups = glob('/sdcard/noGo/*.json')
            for filen in json_backups:
                with open(filen,'r') as fileh:
                    filestr = fileh.read()
                if len(filestr) > 1:
                    name = filen.split('/')[-1]
                    copyfile(filen,'./collections/'+name)

        t1_2 = time()
           
        # Construct GUI
        sm = NogoManager(transition=SlideTransition(direction='left'))
        self.manager = sm
        sm.app = self

        t2 = time()
        print 'CONSTRUCTED manager', t2-t1_2

        # Get initial settings from config panel
        config = self.config
        s1 = time()
        sm.propagate_input_mode(config.getdefault('Board','input_mode','phone'))
        s2 = time()
        sm.propagate_coordinates_mode(config.getdefault('Board','coordinates','1'))
        s3 = time()
        self.stone_type = config.getdefault('Board','stone_graphics','simple')
        s4 = time()
        self.boardtype = config.getdefault('Board','board_graphics','simple')
        s5 = time()
        sm.propagate_boardtype_mode(self.boardtype)
        s6 = time()
        sm.propagate_view_mode(config.getdefault('Board','view_mode','phone'))
        s7 = time()
        self.set_sounds(config.getdefault('Board','sounds','0'))
        s8 = time()
        print s8-s1, s2-s1, s3-s2, s4-s3, s5-s4, s6-s5, s7-s6, s8-s7

        t3_2 = time()

        print 'propagated settings', t3_2 - t2

        # Rebuild homescreen *after* setting phone/tablet mode
        #sm.add_widget(Screen(name='emptyscreen'))
        sm.rebuild_homescreen()
        sm.current = 'Home'

        t3_3 = time()
        print 'rebuilt homescreen', t3_3 - t3_2


        self.bind(on_start=self.post_build_init)

        if platform() == 'android':
            from android import activity
            activity.bind(on_new_intent=self.on_intent)

            self.PythonActivity = autoclass('org.renpy.android.PythonActivity')
            self.ActivityInfo = autoclass('android.content.pm.ActivityInfo')

        t3 = time()
        print 'did android stuff', t3-t3_3
        print 'total init time', t3-t1

        #drawer = NogoDrawer()
        #drawer.add_widget(NavigationButtons())
        # drawer.add_widget(Image(source='media/logo_big2.png',
        #                        allow_stretch=True,
        #                        mipmap=True))
        #drawer.add_widget(sm)

        #self.navdrawer = drawer

        #return drawer
        
        return sm
예제 #44
-1
    def scan_qr(self, on_complete):
        if platform != "android":
            return
        from jnius import autoclass
        from android import activity

        PythonActivity = autoclass("org.renpy.android.PythonActivity")
        Intent = autoclass("android.content.Intent")
        intent = Intent("com.google.zxing.client.android.SCAN")
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE")

        def on_qr_result(requestCode, resultCode, intent):
            if requestCode == 0:
                if resultCode == -1:  # RESULT_OK:
                    contents = intent.getStringExtra("SCAN_RESULT")
                    if intent.getStringExtra("SCAN_RESULT_FORMAT") == "QR_CODE":
                        on_complete(contents)
                    else:
                        self.show_error("wrong format " + intent.getStringExtra("SCAN_RESULT_FORMAT"))

        activity.bind(on_activity_result=on_qr_result)
        try:
            PythonActivity.mActivity.startActivityForResult(intent, 0)
        except:
            self.show_error(
                _("Could not start Barcode Scanner.") + " " + _("Please install the Barcode Scanner app from ZXing")
            )