Pass Service From one Activity to Another - android

how do I pass a service from one activity to another? I have a music player (Activity1) that displays a list of songs, and when you click on it, it starts the service within Activity1. I have a button that users can click that will open Activity2.
So what is the best way for me to pass the service from Activity1 to Activity2. If the service is started in Activity1, then Activity2 should continue playing. If the service is not started in Activity1, then Activity2 should start the service before using it.
Thanks.
Here's some sample code, the MusicService is a class that extends the service class.
public class Activity1 extends AppCompatActivity {
private MusicService serviceMusic;
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.PlayerBinder binder = (MusicService.PlayerBinder) service;
//get service
serviceMusic = binder.getService();
serviceMusic.setSongList(songList);
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
}

I think it would be better to bind service instead of pass a static global service. Since you have multiple activities which will use the same service, a base activity should be created like this:
BasicServiceActivity.java
public abstract class BasicServiceActivity extends AppCompatActivity {
protected DvrService mDvrService;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
attachService();
}
#Override
protected void onDestroy() {
detachService();
super.onDestroy();
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
DvrService.DvrServiceBinder serviceBinder = (DvrService.DvrServiceBinder) binder;
mDvrService = serviceBinder.getService();
onServiceAttached(mDvrService);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mDvrService = null;
}
};
private void attachService() {
Intent service = new Intent(this, DvrService.class);
bindService(service, mServiceConnection, Service.BIND_AUTO_CREATE);
}
private void detachService() {
unbindService(mServiceConnection);
}
/** Callback when service attached. */
protected void onServiceAttached(DvrService service) {
// do something necessary by its subclass.
}
}
Then you can implement subclass activity like this:
public class ServiceActivity extends BasicServiceActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, DvrService.class));
}
#Override
protected void onDestroy() {
if (mDvrService != null) {
mDvrService.removeListener1(mListener1);
}
super.onDestroy();
}
#Override
protected void onServiceAttached(DvrService service) {
// do your stuff, for example add a listener.
service.addListener1(mListener1);
}
}

you can define Application extend class and use public static variable in this class and access this variable in all activity .
like this :
public class G extends Aplication{
public static MusicService serviceMusic;
}
and in manifest :
<application ...
android:name=".G">
Now you can access G.serviceMusic any where.

Related

Access NotificationListenerService class from main activity and vice versa

I need to make a connection between NotificationListenerService class and the MainActivity class. So far service was working independently from the activity and just logged new services. Now I need to connect then to do something with data from the service. More precisely I need to access the getActiveNotification method from the main activity to get notifications and do something with them. And after onNotificationPosted catches notification, add it to recycler view on the main activity. A saw some people do it with a service binder, but can't find how to do that.
Both classes are almost empty so I think there is no need to post them.
I made the connection to the service, how could I now call the addNotificationsToList method from the NotificationListener service??
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private NotificationListener notificationListenerService;
private boolean bound = false;
private static final String tag = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, NotificationListener.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
unbindService(connection);
bound = false;
}
private ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
NotificationListener.LocalBinder binder = (NotificationListener.LocalBinder) service;
notificationListenerService = binder.getService();
bound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};
private void init(){
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new RecyclerViewAdapter();
recyclerView.setAdapter(adapter);
final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(tag, String.valueOf(notificationListenerService.getNum()));
}
});
}
public void addNotificationsToList(StatusBarNotification sbn){
//Add to recyclerView
}
}
public class NotificationListener extends NotificationListenerService {
private final IBinder binder = new LocalBinder();
class LocalBinder extends Binder{
NotificationListener getService(){
return NotificationListener.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public StatusBarNotification[] getActiveNotifications() {
return super.getActiveNotifications();
}
public int getNum(){
return 2;
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
}
}
Read up about bound services. Your Activity can bind to the Service and then it can call methods on the Service that you define using AIDL. In this way the Activity can get data from the Service.

Accessing a variable of a Service

I have an Android Activity called Main that calls a Service called MainService as follows:
Intent intent = new Intent(this, MainService.class);
if(MainService.getInstance() == null){
Log.d(TAG, "Calling MainService");
startService(intent);
}
MainService maintains a variable during its lifetime that I wish to access in Main later on. How do I do this?
Thanks.
You can bind the service and can have the service instance forever. Below sample code will help you:-
Service Class
public class MusicService extends Service {
MyBinder binder=new MyBinder();
MusicService services;
static Context context;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return binder;
}
#Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
MediaPlayer mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.yaar);
mPlayer.start();
}
public class MyBinder extends Binder
{
public MusicService getServiceSystem()
{
return MusicService.this;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Activity
public class MainActivity extends AppCompatActivity {
MusicService services;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ServiceConnection connection=new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MyBinder binderr=(MusicService.MyBinder)service;
services=binderr.getServiceSystem();
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
Intent intent= new Intent(this, MusicService.class);
startService(intent);
}
}
You can then use service anywhere you need in activity. Hope it helps.
Yes, you can access variables inside service, but for that you have to bind to this service first. After that, use accessors for getting or setting variables or call any other method of the service.
See https://developer.android.com/guide/components/bound-services.html

To communicate with Service, what is the different between bindService() and create a instance of service?

To communicate with Service, what is the different between bindService() and create a instance of service? Why should need to use bindService() to communicate with service? I was confused by it.
(1)
public class BLEService extends Service {
private static BLEService sService;
#Override
public void onCreate() {
super.onCreate();
sService = this;
}
public static BLEService getInstance() {
return sService;
}
}
public class HeartRateActivity extends Activity {
private BLEService mBLEService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBLEService = BLEService.getInstance();
}
}
(2)
public class BLEService extends Service {
private final IBinder mBinder = new LocalBinder();
private BLEService mBLEService;
public class LocalBinder extends Binder {
public MyleService getServerInstance() {
return MyleService.this;
}
}
}
public class HeartRateActivity extends Activity {
private BLEService mBLEService;
private boolean mBounded;
#Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, BLEService.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
mBLEService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder)service;
mBLEService = mLocalBinder.getServerInstance();
}
};
}
Thanks
Edit: Remove new operator in onCreate() of service
You would not instantiate a Service object via its constructor using the new keyword. A service is intended to be a long-running process that is not necessarily tied to the lifetime of the Activity that wants access to it. As such, services are something that you use an Intent to signal to Android that you wish to run them in the same way that you use Intent objects to signal that you wish to start a new Activity.
Using .bindService() you can signal to Android that you want to attach to a running service (and to implicitly start that service if it isn't running already). Once bound, you can communicate with the service via whichever interfaces it has available.

Calling activity class method from Service class

I have seen many posts in SO regarding this but could not get the exact and most easy way to call an activity method from service class. Is broadcast receiver only the option? No easy way out ? I just need to call the following method in Activity class after the media player is prepared in Service class .
Activity class:
public void updateProgress() {
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
Service class:
#Override
public IBinder onBind(Intent intent) {
Log.d(this.getClass().getName(), "BIND");
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
try {
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// updateProgress();// Need to call the Activity method here
}
Define an interface your Service will use to communicate events:
public interface ServiceCallbacks {
void doSomething();
}
Write your Service class. Your Activity will bind to this service, so follow the sample shown here. In addition, we will add a method to set the ServiceCallbacks.
public class MyService extends Service {
// Binder given to clients
private final IBinder binder = new LocalBinder();
// Registered callbacks
private ServiceCallbacks serviceCallbacks;
// Class used for the client Binder.
public class LocalBinder extends Binder {
MyService getService() {
// Return this instance of MyService so clients can call public methods
return MyService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public void setCallbacks(ServiceCallbacks callbacks) {
serviceCallbacks = callbacks;
}
}
Write your Activity class following the same guide, but also make it implement your ServiceCallbacks interface. When you bind/unbind from the Service, you will register/unregister it by calling setCallbacks on the Service.
public class MyActivity extends Activity implements ServiceCallbacks {
private MyService myService;
private boolean bound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
}
#Override
protected void onStart() {
super.onStart();
// bind to Service
Intent intent = new Intent(this, MyService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from service
if (bound) {
myService.setCallbacks(null); // unregister
unbindService(serviceConnection);
bound = false;
}
}
/** Callbacks for service binding, passed to bindService() */
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// cast the IBinder and get MyService instance
LocalBinder binder = (LocalBinder) service;
myService = binder.getService();
bound = true;
myService.setCallbacks(MyActivity.this); // register
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
/* Defined by ServiceCallbacks interface */
#Override
public void doSomething() {
...
}
}
Now when your service wants to communicate back to the activity, just call one of the interface methods from earlier. Inside your service:
if (serviceCallbacks != null) {
serviceCallbacks.doSomething();
}
Use Broadcast receiver with service for updating your view from the service class.
For example:
In my activity class
public class ServiceDemoActivity extends Activity {
Intent intent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView notification = (TextView) findViewById(R.id.notification);
if (CheckIfServiceIsRunning()) {
} else {
startService(new Intent(this, MyService.class));
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateDate(intent);
}
};
private void updateDate(Intent intent) {
String time = intent.getStringExtra("time");
Toast.makeText(getApplicationContext(), "Yea!!! Service called", Toast.LENGTH_SHORT).show();
TextView date = (TextView) findViewById(R.id.date);
date.setText(time);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(
MyService.BROADCAST_ACTION));
}
}
And in my service class I am calling my update ui after a few interval of time which updates my UI.
public class MyService extends Service {
public static final String
BROADCAST_ACTION = "com.mukesh.service";
private final Handler handler = new Handler();
#Override
public void onCreate() {
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onDestroy() {
stopService(intent);
}
#Override
public void onStart(Intent intent, int startid) {
int i = 0;
while (i <= 2) {
if (i > 1) {
i++;
this.onDestroy();
} else {
counter = i;
i++;
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1 * 1000); // 1 sec
}
}
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 7 * 1000); // 7 sec
}
};
private void DisplayLoggingInfo() {
intent.putExtra("time", new Date().toLocaleString());
intent.putExtra("counter", String.valueOf(counter));
sendBroadcast(intent);
stopService(intent);
}
}
For complete code check this link
I created a general class called Delegate (it's not a special name, you can name it John) and passed MainActivity class into it as a static field. Then I can access it from the service since its global now. I am not sure if it is cost-effective but it solved the problem for me simple.
My service:
package com.some.package;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
Delegate.theMainActivity.onDeviceTokenChange(token);
}
}
Delegate class:
package com.some.package;
public class Delegate {
static MainActivity theMainActivity;
}
What I did in MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Delegate.theMainActivity = this;
//rest of the code...
}
public void onDeviceTokenChange(String token){
Log.e("updated token:", token);
}
You can't call your sevices method direcly from your activity or vise versa. There are 3 ways to communicate with a service; using broadcasters and receivers, using Messenger or binding to the service. For further information look at http://developer.android.com/guide/components/bound-services.html
You can call from your service
getContentResolver().notifyChange(uri, null);
and in your activity you set up a
getContentResolver().registerContentObserver(uri, false, new ContentObserver(getHandler())
{
public void onChange(boolean selfChange)
{
updateProgress()
}
};
the onChange method will ba called on the UI thread
You can call a method of activity from service by implementing your own listener like this
https://stackoverflow.com/a/18585247/5361964
You might consider running your activity method in runOnUiThread like this:
// method will be called from service
override fun callback(activity: Activity, result: String) {
runOnUiThread{
Toast.makeText(activity, result, Toast.LENGTH_LONG).show()
}
}
I would prefer to use some very easy and cleaner solution provided by
EventBus

How to access 'Activity' from a Service class via Intent?

I am new to Android programming - so I do not have very clear understanding of the 'Context' and the 'Intent'.
I want to know is there a way to access Activity from a Service class?
i.e. Let's say I have 2 classes - one extends from "Activity" and other extends from "Service" and I have created an intent in my Activity class to initiate the service.
Or, how to access the 'Service' class instance from my 'Activity' class - because in such workflow Service class is not directly instantiated by my Activity-code.
public class MainActivity extends Activity {
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, CommunicationService.class));
.
.
}
public class CommunicationService extends Service implements ..... {
.
.
#Override
public int onStartCommand(final Intent intent, int flags, final int startId) {
super.onStartCommand(intent, flags, startId);
....
}
}
You can use bindService(Intent intent, ServiceConnection conn, int flags) instead of startService to initiate the service. And the conn will be a inner class just like:
private ServiceConnection conn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMyService = ((CommunicationService.MyBinder) service).getService();
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
mMyService is the instance of your CommunicationService.
In your CommunicationService, just override:
public IBinder onBind(Intent intent) {
return new MyBinder();
}
and the following class in your CommunicationService:
public class MyBinder extends Binder {
public CommunicationService getService() {
return CommunicationService.this;
}
}
So you can use mMyService to access any public methods and fields in your activity.
In addition, you can use callback interface to access activity in your service.
First write a interface like:
public interface OnChangeListener {
public void onChanged(int progress);
}
and in your service, please add a public method:
public void setOnChangeListener(OnChangeListener onChangeListener) {
this.mOnChangeListener = onChangeListener;
}
you can use the onChanged in your service anywhere, and the implement just in your activity:
public void onServiceConnected(ComponentName name, IBinder service) {
mMyService = ((CommunicationService.MyBinder) service).getService();
mMyService.setOnChangeListener(new OnChangeListener() {
#Override
public void onChanged(int progress) {
// anything you want to do, for example update the progressBar
// mProgressBar.setProgress(progress);
}
});
}
ps: bindService will be like this:
this.bindService(intent, conn, Context.BIND_AUTO_CREATE);
and do not forget
protected void onDestroy() {
this.unbindService(conn);
super.onDestroy();
}
Hope it helps.

Categories

Resources