bring an app to the front when its in the back from a foregroundservice

155 Views Asked by At

note Added

this is my service

as i have edited this shouldnt work on android 13

import kivy
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget 
from jnius import autoclass
import time
from jnius import autoclass, cast
import socket
import pickle
from kivy.utils import platform
from plyer import notification
import sqlite3
from plyer import gps
import requests
import subprocess

PythonService = autoclass('org.kivy.android.PythonService')


while True:

    time.sleep(30)


        #PythonService = autoclass('org.kivy.android.PythonService')
        #mActivity = PythonService.mService
        #intent = autoclass('android.content.Intent')()
        #intent.setClassName(mActivity.getPackageName(), 'org.kivy.android.PythonActivity')
        #intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_SINGLE_TOP | intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
        # i've add this one line below
        #intent.putExtra("allowBackgroundActivityStart", True)
        #mActivity.startActivity(intent)
        #print('started')
        #the code commented above was the original one before the note
        

        #now in here i want retrieve the activity from recent screens or tasklist

        break

and this how i start the service and its runnning as it should

    def start_service_orders(self):
        from android import mActivity
        context =  mActivity.getApplicationContext()
        SERVICE_NAME = str(context.getPackageName()) + '.Service' + 'Lunaser3'
        print('app name ______________________: ' + str(context.getPackageName()))
        service = autoclass(SERVICE_NAME)
        #print(SERVICE_NAME)
        service.start(mActivity,'icon', 'Orders', 'Waiting For a job', '')
        return service
        #print('returned service')

and this the android manifest

<?xml version="1.0" encoding="utf-8"?>
<!-- Replace org.libsdl.app with the identifier of your game below, e.g.
     com.gamemaker.game
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.syncinterpck.syncinter"
      android:versionCode="10211"
      android:versionName="0.1"
      android:installLocation="auto">

    <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:anyDensity="true"
            
            android:xlargeScreens="true"
            
    />

    <!-- Android 2.3.3 -->
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />

    <!-- OpenGL ES 2.0 -->
    <uses-feature android:glEsVersion="0x00020000" />

    <!-- Set permissions -->
    
        <uses-permission android:name="android.permission.INTERNET" />
    
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
        <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <!-- Create a Java class extending SDLActivity and place it in a
         directory under src matching the package, e.g.
            src/com/gamemaker/game/MyGame.java

         then replace "SDLActivity" with the name of your class (e.g. "MyGame")
         in the XML below.

         An example Java class can be found in README-android.txt
    -->
    <application android:label="@string/app_name"
                 android:debuggable="true"
                 android:icon="@mipmap/icon"
                 android:allowBackup="true"
                 
                 
                 android:theme="@android:style/Theme.NoTitleBar"
                 android:hardwareAccelerated="true"
                 android:extractNativeLibs="true" >
      
        <meta-data android:name="wakelock" android:value="0"/>

        <activity android:name="org.kivy.android.PythonActivity"
                  android:label="@string/app_name"
                  android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale|uiMode|uiMode|screenSize|smallestScreenSize|layoutDirection"
                  android:screenOrientation="portrait"
                  android:exported="true"
                  
                  android:launchMode="singleTask"
                  
                  >

            <intent-filter>
            
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            

            
            </intent-filter></activity>
      
        <service android:name="org.syncinterpck.syncinter.ServiceLunaser0"
                 android:process=":service_Lunaser0" />
        
        <service android:name="org.syncinterpck.syncinter.ServiceLunaser3"
                 android:process=":service_Lunaser3" />
 
    </application>

</manifest>

in buildozer here are the services

services = Lunaser0:service.py:foreground, Lunaser3:service2.py:foreground

and this is for Permissions

android.permissions = INTERNET, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, FOREGROUND_SERVICE, SYSTEM_ALERT_WINDOW

this is the adb debug

$ adb logcat -e "Lunaser3" "Intent"
#callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10278; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; allowBackgroundActivityStart: false; intent: Intent { flg=0x30020000 cmp=org.syncinterpck.syncinter/org.kivy.android.PythonActivity (has extras) mCallingUid=10278 }; callerApp: ProcessRecord{5f83a42 9962:org.syncinterpck.syncinter:service_Lunaser3/u0a278}; inVisibleTask: false]
#mactivity started but app stays in the background

i have tried too many solutions but this the further i got into this its said that above android10 the system cant let u start an activity but u can resume one. the logic i have here is to start the app press the home button and wait for the service to bring it up.

In case some one needs the app class to see:

class theapp(App):
    def build(self):
        self.screenm = ScreenManager()

        self.liscreen = liscreen()
        screen = Screen(name = 'liscreen')
        screen.add_widget(self.liscreen)
        self.screenm.add_widget(screen)

        self.acescreen = acescreen()
        screen = Screen(name = 'acescreen')
        screen.add_widget(self.acescreen)
        self.screenm.add_widget(screen)

        self.entryscreen = entryscreen()
        screen = Screen(name = 'entryscreen')
        screen.add_widget(self.entryscreen)
        self.screenm.add_widget(screen)

        self.holderscreen = holderscreen()
        screen = Screen(name = 'holderscreen')
        screen.add_widget(self.holderscreen)
        self.screenm.add_widget(screen)
        
        self.fscreen = fscreen()
        screen = Screen(name = 'fscreen')
        screen.add_widget(self.fscreen)
        self.screenm.add_widget(screen)
        
        return self.screenm

    # def current_location(self, *args):
    #     if platform == 'android': 
    #         from plyer import gps
    #         gps.configure(on_location=self.updatemyloc, on_status=self.on_auth_status)
    #         gps.start(minTime=0, minDistance=0)
    #         print('called')
    
    def updatemyloc(self, *args, **kwargs):
        if 'lat' in kwargs and 'lon' in kwargs:
            gps_lat = kwargs['lat'] 
            gps_lon = kwargs['lon']
            theapp.fscreen.target_lat = kwargs['lat'] 
            theapp.fscreen.target_lon = kwargs['lon']
            print('proof_test______________________________________', gps_lat)
            print('proof_test______________________________________', gps_lon)
        # if self.cnt_ns <= 2:
        #     self.blured_list.append((gps_lat, gps_lon))
        #     print(self.cnt_ns)
        #     self.cnt_ns +=1

        # if self.cnt_ns == 3:
        #     points_counts = Counter(self.blured_list)
        #     most_frequent_point, most_frequent_count = points_counts.most_common(1)[0]
        #     print('cnted')
        #     print(most_frequent_point)
        #     print(most_frequent_count)
        #     self.target_lat = most_frequent_point[0]
        #     self.target_lon = most_frequent_point[1] 
        #     self.blured_list = []
        #     self.cnt_ns = 0

    def on_auth_status(self, general_status, status_messgae):
        if general_status == 'provider-enabled':
            pass        
        else:
            print('enable GPS please')

    def on_resume(self):
        print('____________________-resumed')

    def on_start(self):
        from kivy import platform
        if platform == 'android': 
            from plyer import gps
            gps.configure(on_location=self.updatemyloc, on_status=self.on_auth_status)
            gps.start(minTime=0, minDistance=0)
            print('called')

        Clock.schedule_interval(self.updatemyloc, 0.1)
        conn = sqlite3.connect('LOCALSTATE.db')
        c = conn.cursor()
        c.execute("UPDATE lclstate set name= ?, state=?, lat=?, lon=?, work_rad=?, n_cat=?, cat=?, ang=? WHERE ln=?",('','','','','','','','','1'))
        conn.commit()
        c.close()
        conn.close()
        if platform == "android":
            self.start_service_state()
            self.start_service_orders()
            #print('services started')

    def start_service_state(self):
        from android import mActivity
        context =  mActivity.getApplicationContext()
        SERVICE_NAME = str(context.getPackageName()) + '.Service' + 'Lunaser0'
        print('app name ______________________: ' + str(context.getPackageName()))
        service = autoclass(SERVICE_NAME)
        #print(SERVICE_NAME)
        service.start(mActivity,'icon', 'Status', 'Connected', '')
        return service
        #print('returned service')
               
    def start_service_orders(self):
        from android import mActivity
        context =  mActivity.getApplicationContext()
        print('context____is:', context)
        SERVICE_NAME = str(context.getPackageName()) + '.Service' + 'Lunaser3'
        print('app name ______________________: ' + str(context.getPackageName()))
        service = autoclass(SERVICE_NAME)
        #print(SERVICE_NAME)
        service.start(mActivity,'icon', 'Orders', 'Waiting For a job', '')
        return service
        #print('returned service')

if __name__ == '__main__':
    theapp = theapp()
    #thread_update_state.start()
    #thread_recv_drivers.start()
    #threading.Thread(theapp.run())
    theapp.run()
0

There are 0 best solutions below