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
?
Primitive Data Types To share primitive data between Activities/Services in an application, use Intent. putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism. The android.
A started service can use the startForeground(int, android. app. Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory.
The Service class is the base class for all services. When you extend this class, it's important to create a new thread in which the service can complete all of its work; the service uses your application's main thread by default, which can slow the performance of any activity that your application is running.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With