I want to start 2 services at the start of an activity but only the first one starts and the second fails at bindService(). There is no error just when I want to do something with the service it gives me a nullpointer. I also tried to wait to do something but the service never starts.
The 2 services are pretty similar and I just want to know what is wrong with the implementation. I tried to debug and bindservice() function at startSoundmanagerService return 0, what is maybe the root of the problem but I don't know why.
public class SimulationActivity extends AppCompatActivity {
BluetoothService BService;
boolean mBound = false;
SoundManager SService;
boolean sBound = false;
#Override
protected void onStart() {
super.onStart();
if (bluetoothAdapter.isEnabled()) {
setStatusText("Bluetooth on");
}
else {
setStatusText("Bluetooth off");
}
if(!mBound) {
startServer();
}
conStatImageView.setImageResource(R.drawable.connection_off);
if(!sBound){
startSoundManagerService();
}
#Override
protected void onStop() {
super.onStop();
if(mBound) {
unbindService(bConnection);
mBound = false;
}
if(sBound){
unbindService(sConnection);
sBound = false;
}
}
private ServiceConnection bConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
BluetoothService.LocalBinder binder =
(BluetoothService.LocalBinder) service;
BService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
private ServiceConnection sConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
SoundManager.LocalBinder binder = (SoundManager.LocalBinder) service;
SService = binder.getService();
sBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
sBound = false;
}
public void startServer(){
if (bluetoothAdapter == null) {
Log.d("tag","Device doesn't support Bluetooth") ;
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if(bluetoothAdapter.isEnabled()){
startBluetoothservice();
}
}
private void startBluetoothservice(){
Intent intent = new Intent (this,BluetoothService.class);
bindService(intent, bConnection, Context.BIND_AUTO_CREATE);
Log.i(TAG,"Trying to start bluetoothservice");
}
private void startSoundManagerService(){
Intent intent = new Intent (this,SoundManager.class);
bindService(intent, sConnection, Context.BIND_AUTO_CREATE);
Log.i(TAG,"Trying to start soundservice");
}
So how can I implement 2 different services in 1 activity?
Edit Solution: I forgot to register the service in the manifestfile. ;)
I found the solution: I forgot to register the 2nd Service in the manifest. Thats all ;)
Related
Heres my problem:
I am implementing a music player (PlayerActivity.java / xml) which is bound to a service (PlayerService.java) that basically is just an instance of a musicplayer so that it can run in the background. When lefting the app or changing the activity and the restarting the activity i want to bind to the still running service without stopping or restarting it. I have tried using only bindService() but that made me face the problem: somehow without calling startService() before bindService the Service doesn't get initialized or it takes a few milliseconds so that the functions only get null when accessing service functions.
Here is my service class:
public class playerService extends Service {
public boolean running = false;
public MediaPlayer mediaPlayer;
public boolean isPrepared = false;
private String url;
public class serviceBinder extends Binder {
public playerService getService() {
return playerService.this;
}
}
public boolean isRunning(){
return running;
}
private IBinder mBinder = new serviceBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w("Service", "started");
mediaPlayer = new MediaPlayer();
running = true;
Log.e("!!!", running + "");
return START_STICKY;
}
public void pause() {
mediaPlayer.pause();
}
public void resume() {
mediaPlayer.start();
}
public void setupPlayer() {
try {
if (mediaPlayer != null) {
mediaPlayer.reset();
}
} catch (Exception e) {
Log.e("MediaPlayer", e.getMessage());
}
try {
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.e("MediaPlayerToo", e.getMessage());
}
}
public void reset(){
mediaPlayer.reset();
}
public void updateUrl(String url){
this.url = url;
}
public void start(){
mediaPlayer.start();
}
public int getCurrentPosition(){
return mediaPlayer.getCurrentPosition();
}
public int getDuration(){
return mediaPlayer.getDuration();
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.reset();
}
}
I experimented with waiting until the Service has started with a boolean. But when i add any kind of code
after
mService = binder.getService();
startService(intent);
it seems to not get created at all.
Here is also my onServiceConnected class
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
playerService.serviceBinder binder = (playerService.serviceBinder) service;
Intent intent = new Intent(getApplicationContext(), playerService.class);
mService = binder.getService();
startService(intent);
//... <- adding code here will result in the Service not starting?!!
}
I know that my problem is quite confusing, but this was the best i could come up explaining it. I would be really glad if you had any idea because this problem stops me from deployment. Thank you very much!!
I am using a Service for performing some task, which should run only if the app is in background, moreover the service runs for sometime and after sometime, it gets destroyed. Earlier this was working completely fine, but don't know where i am doing wrong.
Here is the code of my Service:
public class MyService extends Service {
Context context;
public static final String TAG = MyService.class.getSimpleName();
public MyService(Context applicationContext) {
super();
context = applicationContext;
Log.i("myservice", "here service created!");
}
public MyService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "[onCreateService]");
super.onStartCommand(intent, flags, startId);
// Code
registerOverlayReceiver();
context = this;
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterOverlayReceiver();
Log.i("EXIT", "ondestroy!");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void unregisterOverlayReceiver() {
if (myReceiver != null) {
unregisterReceiver(myReceiver);
}
}
private static final String ACTION_DEBUG = "abc.action.DEBUG";
private void registerOverlayReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(ACTION_DEBUG);
registerReceiver(myReceiver, filter);
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "[onReceive]" + action);
if (action.equals(Intent.ACTION_SCREEN_ON)) {
showMyActivity();
} else if (action.equals(ACTION_DEBUG)) {
showMyActivity();
}
}
};
private void showMyActivity() {
Intent intent = new Intent();
intent.setClass(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
I have debugged but couldn't find out the problem for the same.
Anybody who came across anything like this can help me out.
In my application I want to establish a TCP connection with a service and bind this service to every activity where it is needed. It gets started in my Login activity and everything is working like it should. Here is the code:
private TCPService mService;
private boolean mBound = false;
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, TCPService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
TCPService.LocalBinder binder = (TCPService.LocalBinder)service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
Now I want to bind the service in another activity by using almost the same code just without startService(intent); But the mBound is never set to true and I can't access the service functions like it is intented.
Here is the implementation of the service:
public class TCPService extends Service {
private final IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
public TCPService getService() {
return TCPService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return myBinder;
}
}
What am I missing out? Is there anything I should check that may cause this behaviour?
Thanks in advance
I am making a game app but the music still keeps playing even when I closed the game. how to stop? and how to change background music once I go to another activity after I clicked a button
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.rysk);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
this is my main activity (PlayActivity.class)
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
I want to change the music when I clicked a button and went to CatActivity
You should have to work with registerReceiver,unregisterReceiver.
May this helps you.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button btn_startservice;
private Button btn_stopservice;
private TextView tv_servicecounter;
ServiceDemo myService;
boolean isBound;
BroadcastReceiver broadcastRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int datapassed = intent.getIntExtra("value", 0);
tv_servicecounter.setText(String.valueOf(datapassed));
}
};
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_servicecounter = (TextView) findViewById(R.id.tv_activity_main_count);
btn_startservice = (Button) findViewById(R.id.btn_activity_main_startservices);
btn_stopservice = (Button) findViewById(R.id.btn_activity_main_stopservices);
btn_startservice.setOnClickListener(
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);
if (!isBound) {
bindService(objIntent, myConnection, Context.BIND_AUTO_CREATE);
isBound = true;
startService(objIntent);
} else {
isBound = false;
unbindService(myConnection);
}
}
}
);
btn_stopservice.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);
if (isBound) {
isBound = false;
unbindService(myConnection);
stopService(objIntent);
} else {
stopService(objIntent);
}
}
}
);
}
#Override
protected void onResume() {
registerReceiver(broadcastRec, new IntentFilter("USER_ACTION"));
super.onResume();
}
#Override
protected void onStop() {
this.unregisterReceiver(broadcastRec);
super.onStop();
}
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
myService = ((ServiceDemo.MyLocalBinder) service).getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
if (isBound) {
unbindService(myConnection);
isBound = false;
}
}
}
And ServiceDemo.java
public class ServiceDemo extends Service {
int i;
private MyThread mythread;
public boolean isRunning = false;
Notification notification;
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
mythread = new MyThread();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
if (!isRunning) {
mythread.start();
isRunning = true;
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mythread.interrupt();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
public void sendBrodcastMsg(int value) {
Intent intent = new Intent();
intent.setAction("USER_ACTION");
intent.putExtra("value", value);
sendBroadcast(intent);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
class MyThread extends Thread {
static final long DELAY = 100;
#Override
public void run() {
while (isRunning) {
try {
i++;
Thread.sleep(DELAY);
sendBrodcastMsg(i);
shownotification();
} catch (InterruptedException e) {
isRunning = false;
e.printStackTrace();
}
}
stopSelf();
}
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void shownotification() {
Intent in = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), in, 0);
notification = new NotificationCompat.Builder(this)
.setContentTitle(String.valueOf(i))
.setContentText(String.valueOf(i))
.setSmallIcon(R.drawable.musicplayer)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
;
startForeground(101, notification);
}
public class MyLocalBinder extends Binder {
ServiceDemo getService() {
return ServiceDemo.this;
}
}
private final IBinder myBinder = new MyLocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return myBinder;
}
}
put this two lines in manifest.
<service android:name=".ServiceDemo"
android:enabled="true"/>
You need to stop the player in onPause(). Following code can be used:
#Override
protected void onPause() {
super.onPause();
if (this.isFinishing()){
player.stop();
}
}
Check Android Stop Background Music for more details
for that you should stop the service in the onCreate method of the Activity. Below is the code for it :
stopService(new Intent(MyService.MY_SERVICE));
Best of Luck!
In Your MainActivity , You Should Call stopService() Inside MainActivity
#Override
public void OnPause() {
stopService(svc);
}
How to pass handler from an activity to service? I am trying to update the activity UI on the state of Bluetooth connection by using Handler as shown below from service class.
mHandler.obtainMessage(MenuActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
In the activity, I implemented this:
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (true)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch(msg.arg1){
case BluetoothService.STATE_CONNECTED:
showToast("Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT);
break;
I tried to use a constructor to pass the handler from the activity to service like this:
public BluetoothService(Handler handler, BluetoothAdapter mBluetoothAdapter) {
mAdapter = mBluetoothAdapter;
mState = STATE_NONE;
mHandler = handler;
}
But there was an error which shows Unable to instantiate service and found that the service needs to have a public no-args constructor. But after removing the constructor, the handler did not get passed into the service.
How to solve this problem?
You have to bind to the service from activity and establish a ServiceConnection and then get the instance of service and set your handler.
Here is the activity and service class which i use for one of my media player application.....
public class MainActivity extends Activity
{
private CustomService mService = null;
private boolean mIsBound;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
startService(new Intent(this.getBaseContext(), CustomService.class));
doBindService();
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
mService = ((CustomService.LocalBinder)iBinder).getInstance();
mService.setHandler(yourHandler);
}
#Override
public void onServiceDisconnected(ComponentName componentName)
{
mService = null;
}
};
private void doBindService()
{
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(this,
CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService()
{
if (mIsBound)
{
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
doUnbindService();
}
}
CustomService Code ....
public class CustomService extends Service
{
private final IBinder mIBinder = new LocalBinder();
private Handler mHandler = null;
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flag, int startId)
{
return START_STICKY;
}
#Override
public void onDestroy()
{
if(mHandler != null)
{
mHandler = null;
}
}
#Override
public IBinder onBind(Intent intent)
{
return mIBinder;
}
public class LocalBinder extends Binder
{
public CustomService getInstance()
{
return CustomService.this;
}
}
public void setHandler(Handler handler)
{
mHandler = handler;
}
}