React Native keep location tracking and websocket active when app is on background

i have a project in react native that sends via websocket real-time coordinates via a node backend server and after im receiving them from a react frontend page. The problem i have is that when the app is in background the websocket wont work also location tracking. Any ideas?

Backend Code:

// Import the 'ws' (WebSocket) module
const WebSocket = require('ws');

// Create a new WebSocket server instance, listening on port 8080
const wss = new WebSocket.Server({ port: process.env.PORT || 8080 });

// Initialize an array to store coordinates
const coordinates = [];

// Event listener for when a client connects to the server
wss.on('connection', function connection(ws) {
  console.log('A new client connected');

  // Event listener for when a message is received from a client
  ws.on('message', function incoming(message) {
    console.log('Received: %s', message);

    // Parse the incoming message (assuming it's JSON)
    try {
      const data = JSON.parse(message);
      // Push the coordinates to the array
      coordinates.push(data);
      
      // Broadcast the message to all connected clients
      wss.clients.forEach(function each(client) {
        if (client !== ws && client.readyState === WebSocket.OPEN) {
          // Send the message to all clients except the sender
          client.send(JSON.stringify(data));
        }
      });
    } catch (error) {
      console.error('Error parsing message:', error);
    }
  });

  // Event listener for when the connection is closed
  ws.on('close', function close() {
    console.log('Client disconnected');
  });

  console.log('WebSocket server listening on port 8080');
});

and React Native code:

 const wsRef = useRef(null);

  useEffect(() => {
    // Establish WebSocket connection
    wsRef.current = new WebSocket('wss://websocketa-52220f631af2.herokuapp.com/');

    // Event handler for when WebSocket connection is open
    wsRef.current.onopen = () => {
      console.log('WebSocket connected');
    };

    // Event handler for when WebSocket receives a message
    wsRef.current.onmessage = (event) => {
      console.log('Received message:', event.data);
    };

    // Event handler for WebSocket errors
    wsRef.current.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    // Clean up WebSocket connection on component unmount
    return () => {
      wsRef.current.close();
    };
  }, []);

  // Function to send location data to the server
  const sendLocationToServer = (latitude, longitude) => {
    if (wsRef.current) {
      wsRef.current.send(JSON.stringify({ latitude, longitude }));
    }
  };

  // Request permission to access location
  const handleConnectButtonPress = () => {
    // Run getCurrentPosition immediately
    getCurrentPosition();
    // Run getCurrentPosition every 5 seconds
    setInterval(getCurrentPosition, 5000);
    showLocationServiceNotification();

  };
  // Get the current position
  const getCurrentPosition = () => {
    Geolocation.getCurrentPosition(
      position => {
        const { latitude, longitude } = position.coords;
        console.log('Latitude:', latitude);
        console.log('Longitude:', longitude);
        // Send location data to the server
        sendLocationToServer(latitude, longitude);
      },
      error => {
        console.log('Error getting location:', error);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  };

  const showLocationServiceNotification = () => {
    PushNotification.localNotification({
      channelId: 'location-service-channel',
      title: 'Location Service',
      message: 'Location service is running in the background.',
    });
  };
    // Request permission to access location

  useEffect(() => {
    Geolocation.requestAuthorization();
  }, []);

and the manifest:


    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

I tried to install some libraries like react-native-geolocation but couldn’t find a solution..

New contributor

Ioannis Kaldellis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật