Search code examples
androidservicerefer

Refer an integer from Service to Service


I am building an app which needs to pass an integer from one service to an other service.

FirstService

package com.jebinga.MyApp;



import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;





public class FirstService extends Service implements SensorEventListener {

int Value1=10;



@Override
    public void onCreate() {
    super.onCreate();





     Bundle korb=new Bundle();
        korb.putInt("Ente", Value1);

        Intent in = new Intent(FirstService.this, SecondService.class);
        in.putExtra("korb", korb);
        this.startService(in); 


         System.err.println("FirstService Value1: "+Value1); 




    }




    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }



}

SecondService

package com.jebinga.MyApp;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.util.Log;

public class SecondService extends Service{



    int Value2;








 public void onStartCommand(Intent intent, int startId){
         super.onStartCommand(intent, startId, startId);



         Bundle zielkorb = intent.getExtras();
         int Value2 = zielkorb.getInt("Ente");



         System.err.println("SecondService Value2:="+Value2); 





         }





    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

Due to the log I know that value1 in FirstService is 10 as it should be. But value2 is 0 though it should also be 10.

What did I do wrong? Anyone can help me?


Solution

  • You packed a bundle into an intent, and then a value into that bundle. So you need to read them out, first the bundle, and then the value.

    Bundle zielkorb = intent.getBundleExtra("korb");
    int bValue = zielkorb.getInt("Ente");