How to call service from service callback - java

I have a java background serviceA and serviceB. I have instantiated serviceA in onStart method in Mainactivity class . I need to start serviceB if the serviceA fails to start. I have written a callback method which gets called in MainActivity but when I tried to call serviceB it is not getting created.
I have written a callback method in MainActivity which gets called in serviceA but when I tried to call serviceB it is not getting created.
public class MainActivity extends Activity implements ServiceCallbacks{
private static final String TAG = "Main Activity";
private Context myContext = null;
Intent myTestService;
private MyTestService serviceA;
private boolean bound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myContext = this;
setContentView(R.layout.activity_main);
Log.d(TAG,"onCreate called.");
}
#Override
protected void onResume() {
super.onResume();
if(serviceA == null) {
serviceA = new Intent(this, MyTestService.class);
Log.d(TAG,"onResume called.");
Log.d(TAG,"myTestService instance created.");
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG,"onPause called.");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG,"OnDestory called");
}
#Override
protected void onStart() {
super.onStart();
// bind to Service
Intent intent = new Intent(this, MyTestService.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(MainActivity.this); // register
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
#Override
public void callBackToActivity() {
unbindService(serviceConnection);
StartNewService();
}
private void StartNewService(){
Intent intent = new Intent(this, serviceB.class);
startService(intent);
}
}
I want to start serviceB if serviceA fails to start.
I am c# developer and new to java and need your help.

Related

moving the code to the activity java class (making two java classes into one)

I have codes in two classes
First class is ExampleBroadcastReceiver:
public class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
Toast.makeText(context, "Disconnected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
Second class is MainActivity:
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver = new ExampleBroadcastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}
How can I make the two classes into one by passing the code from the ExampleBroadcastReceiver class to MainActivity? Is it possible? Please don't ask why. Thanks.
Use java interface to handle an event in MainActivity that occurs in ExampleBroadcastReceiver. This way you don't have to merge classes to share an event based data.
public class ExampleBroadcastReceiver extends BroadcastReceiver {
public interface ConnectivityMonitorCallback {
void onConnectivityChanged(boolean connectivity);
}
public ConnectivityMonitorCallback callback;
public ExampleBroadcastReceiver(#NonNull ConnectivityMonitorCallback eventCallback) {
callback = eventCallback;
}
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
callback.onConnectivityChanged(noConnectivity);
}
}
}
Finally in the MainActivity you handle the event.
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define event handling code here which occurs in ExampleBroadcastReceiver
exampleBroadcastReceiver = new ExampleBroadcastReceiver(new ExampleBroadcastReceiver.ConnectivityMonitorCallback {
#Override
void onConnectivityChanged(boolean connectivity) {
// Handle the event that occured in ExampleBroadcastReceiver
}
});
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}

How to remove Manifest internal service error

I have declared my Service inside my Voice Activity's Voice.java that
public class Voice extends AppCompatActivity implements RecognitionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
startService(new Intent(Voice.this,task.class));
}
class task extends Service{
#Override
public void onCreate() {
//background code here
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and my manifest showing
this error
Instantiatable attribute missing

Android bound service onStart does not work

I have a Service (Bound) which I am trying to start from my MainActivity.java. The below is my Main Activity code:
public class MainActivity extends AppCompatActivity {
Handler m_handler;
Runnable m_handlerTask ;
private static ServiceConnection sConnection;
static boolean serviceBound = false;
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, DataDownloaderService.class);
bindService(intent, sConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (!Global.isMyServiceRunning(DataDownloaderService.class, this)) {
sConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
DataDownloaderService.LocalBinder binder = (DataDownloaderService.LocalBinder) service;
Global.dService = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
serviceBound = false;
}
};
}
}
catch(Exception ex ){
String p="";
}
}
#Override
protected void onResume(){
super.onResume();
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
RefreshNowPlaying();
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
}
void RefreshNowPlaying(){
//Do something
}
}
The service code is as shown below:
public class DataDownloaderService extends Service {
private final IBinder dBinder = new LocalBinder();
public class LocalBinder extends Binder {
DataDownloaderService getService() {
// Return this instance of LocalService so clients can call public methods
return DataDownloaderService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return dBinder;
}
#Override
public void onCreate(){
}
#Override
public void onStart(Intent intent, int startid){
super.onStart(intent,startid);
Global.DataDownloaderServiceStatus = "STARTED";
}
#Override
public void onDestroy(){
Global.DataDownloaderServiceStatus = "STOPPED";
super.onDestroy();
}
}
I have also added the service to the AndroidManifest.xml under the Application element. However, I see that the service's onStart is never fired or the override onServiceConnected in the MainActivity is never called. I am new to Anrdoid development and Java. Can someone give me some pointers, please? I have noticed that the service's onCreate is getting hit, by putting breakpoints, but not onStart.
onStart() will be called only if the service was started via context.startService(), see here.

Not able to function the media player properly in the background services

I have implemented the media player in my project and I want to play the music even when I close my application , but when I kill my application then it should stop playing the music.
My problem which I am facing is that my application starts playing the music again with the previous one playing already whenever I open my unkilled application again.What am i doing wrong ??
My requirement is that the music should start playing as soon as i open the app,and it should keep on playing in the background even if i close(not killed) my app.But when i kill my app then the music should stop playing
Here is my code -
Main_activity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String msg = "Android : ";
private Button play,pause,restart;
LocalService mService;
boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button) findViewById(R.id.play);
pause=(Button) findViewById(R.id.pause);
restart=(Button) findViewById(R.id.restart);
play.setOnClickListener(this);
pause.setOnClickListener(this);
restart.setOnClickListener(this);
Intent intent = new Intent(this, LocalService.class);
startService(intent);
}
/** Called when the activity is about to become visible. */
#Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
/** Called when the activity has become visible. */
#Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event");
}
/** Called when another activity is taking focus. */
#Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event");
}
/** Called when the activity is no longer visible. */
#Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}
/** Called just before the activity is destroyed. */
#Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
Log.d("mbound value",mBound+"");
if (mBound) {
Intent intent=new Intent(this,LocalService.class);
stopService(intent);
unbindService(mConnection);
mBound = false;
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case(R.id.play):
if(mBound)
mService.start_mp();
break;
case(R.id.pause):
if(mBound)
mService.pause_mp();
break;
case (R.id.restart):
if(mBound)
mService.restart_mp();
break;
default:
break;
}
}
/** Defines callbacks for service binding, passed to bindService() */
public ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
LocalService.java
public class LocalService extends Service {
private MediaPlayer mediaPlayer;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.i("Onbind called","");
return mBinder;
}
/** Called when the service is being created. */
#Override
public void onCreate() {
super.onCreate();
mediaPlayer=MediaPlayer.create(this,R.raw.jingle);
}
/** The service is starting, due to a call to startService() */
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
/** Called when all clients have unbound with unbindService() */
#Override
public boolean onUnbind(Intent intent) {
return true;
}
/** Called when a client is binding to the service with bindService()*/
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
/** Called when The service is no longer used and is being destroyed */
#Override
public void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
public void start_mp(){
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
}
public void pause_mp(){
mediaPlayer.pause();
}
public void restart_mp(){
if(mediaPlayer.isPlaying()) mediaPlayer.release();
mediaPlayer=MediaPlayer.create(this,R.raw.jingle);
mediaPlayer.start();
}
}
P.S.-I have applied the buttons in my application for the player functionality inside my app .
I got the solution.Whenever I press my homebutton ,then my onstop() method is executed and I get whatever I aim at,on pressing back button the default action of android is to destroy the activity.
Pressing the default back button of android device will call the finish() method of the activity and hence OnDestroy() will be called,by pressing the HomeButton the OnStop() method will be called.

android bindService() NullPointerException

The following code keeps throwing null pointer exception...
public class MainActivity extends Activity implements OnClickListener{
Button but;
Button but2;
LocalBinder binder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but = (Button) findViewById(R.id.button1);
but.setOnClickListener(this);
but = (Button) findViewById(R.id.button2);
}
ServiceConnection connection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
Log.d("D1", "connecting");
binder = (LocalBinder) arg1;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
Log.d("D1", "disconnecting");
}
};
public static class ServiceTest extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return new LocalBinder();
}
public class LocalBinder extends Binder{
public void toast(){
Toast.makeText(getApplicationContext(), "hope this works", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ServiceTest.LocalBinder.class);
bindService(i, connection, Context.BIND_AUTO_CREATE);
Toast.makeText(getApplicationContext(), "bind completed", Toast.LENGTH_LONG).show();
}
public void binderMethod(View v){
binder.toast();
}
}
I guess that the reason is that onServiceConnected does not execute, which causes binder to stay null. (The but button binds the service to the activity while but2 executes binder.toast(); - the exception is thrown when but2 is pressed)
Basicly the question is : why doesnt onServiceConnected execute ?
I think, that intent should lead to service, not binder in service: Intent i = new Intent(getApplicationContext(), ServiceTest.class);

Categories