Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

binding - Android: pass parameter to Service from Activity

I'm binding to Service by this way:

Activity class:

ListenLocationService mService;
@Override
public void onCreate(Bundle savedInstanceState) {
        ...
        Intent intent = new Intent(this, ListenLocationService.class);
        intent.putExtra("From", "Main");
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        ...
}

private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                IBinder service) {
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();         
        }

        public void onServiceDisconnected(ComponentName arg0) {
        }
    };

This is onBind method of my Service:

@Override
public IBinder onBind(Intent intent) {
    Bundle extras = intent.getExtras(); 
    if(extras == null)
        Log.d("Service","null");
    else
    {
        Log.d("Service","not null");
        String from = (String) extras.get("From");
        if(from.equalsIgnoreCase("Main"))
            StartListenLocation();
    }
    return mBinder;
}

So I have "null" in LogCat - bundle is null in spite of I made intent.putExtra before bindService

In general Service works fine. However I need to call StartListenLocation(); only from main activity of application (I decide to do this by sending a flag).

How can I send a data to service?Or maybe there's another way to check what activity launched onBind?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can pass the parameter in this simple way:-

Intent serviceIntent = new Intent(this,ListenLocationService.class); 
   serviceIntent.putExtra("From", "Main");
   startService(serviceIntent);

and get the parameter in onStart method of your service class

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Bundle extras = intent.getExtras(); 
    if (extras == null) {
        Log.d("Service","null");
    else {
        Log.d("Service","not null");
        String from = (String) extras.get("From");
        if(from.equalsIgnoreCase("Main"))
        StartListenLocation();
    }
}

Enjoy :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...