jamesisaac / react-native-background-task

Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.
MIT License
1.1k stars 110 forks source link

Expected to run on UI thread! #14

Open sandropoluan opened 6 years ago

sandropoluan commented 6 years ago

Expected to run on UI thread! I got that error.

My code

BackgroundTask.define(async () => { 
              try{ 
                  navigator.geolocation.getCurrentPosition(
                    async (position)=>{                       
                        fetch(publicUrl+'/posisi_members',{
                          method:'post',
                          credentials:'include',
                          headers:{
                             'Accept': 'application/json',
                             'Content-Type': 'application/json',
                          },
                          body:JSON.stringify({
                            latitude:position.coords.latitude,
                            longitude:position.coords.longitude,
                            test:true,
                          }), 
                        }).then(response=>{}).catch(error=>{});

                    },(error)=>{},{enableHighAccuracy: false, timeout: 20000, maximumAge: 100000});

              } catch (error){

              }    
            ;
})
jamesisaac commented 6 years ago

My guess is this would be to do with navigator.geolocation.getCurrentPosition being code which can't be run in the background. If you take out that line, and make the same fetch request with a dummy value for position, presumably it works?

jamesisaac commented 6 years ago

I would recommend using a more specific library for this purpose, e.g.: https://github.com/transistorsoft/react-native-background-geolocation

artemukolov commented 6 years ago

I have this problem and I don't use navigator.geolocation at all. "react-native-background-task": "^0.2.1", "react-native": "^0.48.4",

jamesisaac commented 6 years ago

@artemukolov What code are you trying to execute in your task?

artemukolov commented 6 years ago

So. Looks like I fix it by update RN to 49.5. But this requires React 16.beta.5 Be careful.

stefanlenoach commented 6 years ago

Has anyone found a different solution for this issue besides upgrading to RN 49.5 with React 16.beta.5? This is my background task:

BackgroundTask.define(() => { console.log('Hello from a background task') BackgroundTask.finish() }).

It looks like it works when the app is in the background, but if I kill it then I get the 'Expected to run on UI thread' error. I tried commenting out the console log but the issue persists.