react-native-background-geolocation icon indicating copy to clipboard operation
react-native-background-geolocation copied to clipboard

Location not getting when device in sleep mode or screen lock

Open GurjeetLamba opened this issue 2 years ago • 11 comments

Your Environment

  • Plugin version:4.12.1
  • Platform: Android
  • OS version:
  • Device manufacturer / model: OPPO/CPH2095
  • React Native version (react-native -v): 0.64
  • Plugin config

import PushNotification, { Importance } from 'react-native-push-notification'; import { PermissionsAndroid, Alert } from 'react-native'; import RNLocation from 'react-native-location'; import { apiService } from '../../services/api.service'; import RNSettings from 'react-native-settings'; import { AppStorage, key } from '../../services/async-storage'; import moment from 'moment'; import Geolocation from 'react-native-geolocation-service'; import axios from 'axios'; import BackgroundGeolocation, { Location, Subscription } from "react-native-background-geolocation" //import BackgroundGeolocation from '@mauron85/react-native-background-geolocation'; class NotificationHandler { async onNotification(notification) { console.log("notification received", notification)

if (notification.data.title === "silent notification") {
  if (Platform.OS === "ios") {
    console.log("Platform", Platform.OS)
  }
  else if (Platform.OS === "android" && notification.data.title == "silent notification") {
    // ============silent notification code============
    const hasBackgroundPermissions = await PermissionsAndroid.check(
      PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION,
    );
    const hasforegroundPermissions = await PermissionsAndroid.check(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    );

    let locationSubscription = null;
    let locationTimeout = null;
    if (hasBackgroundPermissions && hasforegroundPermissions) {
      RNSettings.getSetting(RNSettings.LOCATION_SETTING).then(async (result) => {
        if (result == RNSettings.ENABLED) {

          console.log('GPS is on');
          BackgroundGeolocation.ready({
            desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
       
            stopTimeout: 5,
            // Application config
            debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
            logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
            stopOnTerminate: false,   // <-- Allow the background-service to continue tracking when user closes the app.
            startOnBoot: true,        // <-- Auto start tracking when device is powered-up.
            // HTTP / SQLite config
            url: 'http://yourserver.com/locations',
            batchSync: false,       // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
            autoSync: true,         // <-- [Default: true] Set true to sync each location to server as it arrives.
            headers: {              // <-- Optional HTTP headers
              "X-FOO": "bar"
            },
            params: {               // <-- Optional HTTP params
              "auth_token": "maybe_your_server_authenticates_via_token_YES?"
            }
          }).then(async (state) => {
            // YES -- .ready() has now resolved.
            let locations = await BackgroundGeolocation.getCurrentPosition({
              timeout: 30,          // 30 second timeout to fetch location
              persist: true,        // Defaults to state.enabled
              maximumAge: 5000,     // Accept the last-known-location if not older than 5000 ms.
              desiredAccuracy: 10,  // Try to fetch a location with an accuracy of `10` meters.
              samples: 3,           // How many location samples to attempt.
              extras: {             // Custom meta-data.
                "route_id": 123
              }
            });
            BackgroundGeolocation.start();
            console.log("location", locations)
            if (locations.coords.latitude) {
              console.log("location", locations)
              let timestamp = new Date();

              const formatedDate = moment.utc(timestamp).format('YYYY/MM/DD hh:mm:ss A');
              let respo_storage = await AppStorage.getToken();
              const requestdata = {
                ClientId: respo_storage.data.ClientId,
                Latitude: locations.coords.latitude,
                Longitude: locations.coords.longitude,
                TimeStamp: formatedDate,
                Unique: notification.data.message
              }
              console.log("location params in notification handler", requestdata)
              apiService.post('SAVELOCATION', requestdata).then(
                (response) => {
                  console.log("updated location response", response)
                  if (response.data.Success) {
                    // BackgroundGeolocation.stop();
                  }
                  else {
                    console.log(response.data.Message)
                  }
                },
                (error) => {
                  console.log("Error", error)
                  if (error) {
                    if (error == 'Unauthorized access') {
                      Alert.alert('Warning!', 'Session expired. Please login again', [
                        {
                          text: 'OK',
                          onPress: () => console.log("Session expired"),
                        },
                      ]);
                    } else {
                      Alert.alert('Warning!', error, [
                        {
                          text: 'OK',
                        },
                      ]);
                    }
                  }
                },
              );
            }
            else {
              console.log("location error")
          

            }
          })

          

        } else {
          console.log("Permissoion 1")
          this.sendPermissionStatus();
        }
      });
    }
    else {
      console.log("Permissoion 2")
      this.sendPermissionStatus();
    }
  }

}

if (typeof this._onNotification === 'function') {
  this._onNotification(notification);
}

}

sendPermissionStatus = async () => { let loginResponse = await AppStorage.getClientId(); const clientId = loginResponse.data.ClientId; let timestamp = new Date(); const formatedDate = moment.utc(timestamp).format('YYYY/MM/DD hh:mm:ss A'); console.log("New timestamp parameter handler", formatedDate); const data = { ClientId: clientId, PermissionStatus: "N", TimeStamp: formatedDate } console.log("Location Permission Params", data) apiService .post('SETLOCATIONPERMISSION', data) .then( (response) => { if (response.data.Success) {

      }
    },
    (error) => {
      if (error) {
        Alert.alert('Warning!', error, [
          {
            text: 'OK',
            onPress: () => 'ok pressed',
          },
        ]);
      }
    },
  );

} onRegister(token) { console.log("token", token) if (typeof this._onRegister === 'function') { this._onRegister(token); } }

onAction(notification) { if (notification.action === 'Yes') { PushNotification.invokeApp(notification); } }

// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS) onRegistrationError(err) { console.log(err); }

attachRegister(handler) { this._onRegister = handler; }

attachNotification(handler) { console.log("notification handler") this._onNotification = handler; } }

const handler = new NotificationHandler();

PushNotification.createChannel( { channelId: "1", // (required) channelName: "My channel", // (required) channelDescription: "A channel to categorise your notifications", // (optional) default: undefined. playSound: false, // (optional) default: true soundName: "default", // (optional) See soundName parameter of localNotification function importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance vibrate: true, // (optional) default: true. Creates the default vibration pattern if true. }, (created) => console.log(createChannel returned '${created}') // (optional) callback returns whether the channel was created, false means it already existed. ); PushNotification.configure({ // (optional) Called when Token is generated (iOS and Android) onRegister: handler.onRegister.bind(handler),

// (required) Called when a remote or local notification is opened or received onNotification: handler.onNotification.bind(handler),

// (optional) Called when Action is pressed (Android) onAction: handler.onAction.bind(handler),

// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS) onRegistrationError: handler.onRegistrationError.bind(handler),

// IOS ONLY (optional): default: all - Permissions to register. permissions: { alert: true, badge: true, sound: true, },

// Should the initial notification be popped automatically // default: true popInitialNotification: true,

/**

  • (optional) default: true
    • Specified if permissions (ios) and token (android and ios) will requested or not,
    • if not, you must call PushNotificationsHandler.requestPermissions() later */ requestPermissions: true, });

export default handler;

Expected Behavior

Actual Behavior

Steps to Reproduce

Context

I am calling Background geolocation code on receive of silent notifications which awake the app in background , It is working fine when screen is not locked , I am getting beep sound everytime location is fetched , but device screen is locked no beep sound and no location update in db

GurjeetLamba avatar Jun 26 '23 11:06 GurjeetLamba

See https://dontkillmyapp.com

christocracy avatar Jun 26 '23 11:06 christocracy

Also see wiki “Philosophy of Operation”

christocracy avatar Jun 26 '23 11:06 christocracy

See https://dontkillmyapp.com

Already tried these steps

GurjeetLamba avatar Jun 26 '23 11:06 GurjeetLamba

I have no idea what is wrong with your device.

christocracy avatar Jun 26 '23 11:06 christocracy

Does this library work individually without react-native-background-fetch

Background-fetch is required to be configured as documented in the Setup Instructions. Implementing in JavaScript is optional.

See wiki “Debugging” and learn to observe logs from the plug-in.

christocracy avatar Jun 26 '23 12:06 christocracy

Where can I find wiki debugging option? In documentation or I need to search on google ?

On Mon, 26 Jun 2023 at 17:30, Chris Scott @.***> wrote:

Does this library work individually without react-native-background-fetch

Background-fetch is required to be configured as documented in the Setup Instructions. Implementing in JavaScript is optional.

See wiki “Debugging” and learn to observe logs from the plug-in.

— Reply to this email directly, view it on GitHub https://github.com/transistorsoft/react-native-background-geolocation/issues/1721#issuecomment-1607322551, or unsubscribe https://github.com/notifications/unsubscribe-auth/ADHU5NOWVV2YYECLBAPH4CLXNF2XPANCNFSM6AAAAAAZUAR2MI . You are receiving this because you authored the thread.Message ID: <transistorsoft/react-native-background-geolocation/issues/1721/1607322551 @github.com>

GurjeetLamba avatar Jun 26 '23 13:06 GurjeetLamba

Read the Wiki here “Debugging”. See api docs Logger.

christocracy avatar Jun 26 '23 13:06 christocracy

Screenshot 2023-06-26 at 9 29 41 AM

christocracy avatar Jun 26 '23 13:06 christocracy

TransistorAuthorizationToken is only for demo/testing purposes. When you provide that, the plugin IGNORES your provided url and automatically sends locations to https://tracker.transistorsoft.com

If you want locations to arrive at your url:"http://92.204.135.120:8099/TomAPI/SaveLocationInformation", then DELETE this line:

  transistorAuthorizationToken: token,

Does this library Track location when person is moving only ,Because when we were still it was not uploading any location ?

It's all explained in the Philosophy of Operation I told you to read above. It's pretty clearly stated in the first paragraph.

Screenshot 2023-06-27 at 11 20 04 AM

christocracy avatar Jun 27 '23 15:06 christocracy

GitHub issues are not open-ended support threads for every issue you have. They are for specific issues according to the subject of the issue Location not getting when device in sleep mode or screen lock.

You are creating a chaotic mess of this issue. Is your original issue solved?

christocracy avatar Jun 28 '23 12:06 christocracy

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] avatar May 20 '24 01:05 github-actions[bot]

This issue was closed because it has been inactive for 14 days since being marked as stale.

github-actions[bot] avatar Jun 03 '24 01:06 github-actions[bot]