Search code examples
androidsocket.iobackground-service

How to the send data to the Activity from background service?


I want to send data to app activity from background service.How can I do that? I fetch data with socketio on my background service.And I need use this data in my activity class dinamically


Solution

  • use BroadcastReceiver

    in your Service

    private void sendMessageToActivity(String newData){
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("ServiceToActivityAction");
            broadcastIntent.putExtra("ServiceToActivityKey", newData);
            sendBroadcast(broadcastIntent);
    }
    

    in your Activity

    private ServiceToActivity serviceReceiver;
    @Override  
    public void onCreate(Bundle savedInstanceState)   
    {  
    ...  
    
        serviceReceiver = new ServiceToActivity();  
        IntentFilter intentSFilter = new IntentFilter("ServiceToActivityAction");  
        registerReceiver(serviceReceiver, intentSFilter);  
    
    
    
    ...  
    }  
    
    public class ServiceToActivity extends BroadcastReceiver  
    {  
        @Override   
        public void onReceive(Context context, Intent intent)  
        {  
             Bundle notificationData = intent.getExtras();  
             String newData  = notificationData.getString("ServiceToActivityKey");  
    
             // newData is from the service
    
        }  
     }
    
    @Override  
    protected void onDestroy()   
    {  
        ...  
    
        unregisterReceiver(serviceReceiver);  
    
    
        ...  
    }
    

    in your AndroidManifest.xml

    <manifest ... >
      ...
      <application ... >
          <service android:name="com.your-package.ServiceToActivity" />
          ...
      </application>
    </manifest>
    

    Use AlarmManager to schedule work. inside your Service

    private void scheduleAlarm()
    {
        // acquire wakelock
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.acquire();
        try{
        // The time at which the alarm will be scheduled. 
        // example every 30 secs = 30000 long as time
        Long time = timeToFetchData;
    
        // Create an Intent and set the class that will execute when the Alarm triggers. Here we have
        // specified AlarmReceiver in the Intent. The onReceive() method of this class will execute when the broadcast from your alarm is received.
        Intent intentAlarm = new Intent(this, AlarmReceiver.class);
    
        // Get the Alarm Service.
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
        // Set the alarm for a particular time.
        alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
        Toast.makeText(this, "Alarm Scheduled for 30 seconds", Toast.LENGTH_LONG).show();       
       }catch(Exception ex){}
       finally{
          // release wake lock
          mWakeLock.release();
    
       }
    }
    
    public class AlarmReceiver extends BroadcastReceiver
    {
         @Override
         public void onReceive(Context context, Intent intent)
         {
    
             // Your code to execute when the alarm triggers
             // and the broadcast is received.   
             // perform your operations here.
    
             // we need to reschedule again
             // set the timeToFetchData
             // call scheduleAlarm
             timeToFetchData = 30000;
             scheduleAlarm();
         }
    }
    

    hope it helps :)