1

i know that services can be started from Activity as below

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   // Method to start the service
   public void startService(View view) {
      startService(new Intent(getBaseContext(), MyService.class));
   }
}

as the startService( ) method is there in Activity class, i am thinking its not possible to call service from any java class which is not extending activity class... if there any way we can start the service from a normal/Utility class, plz let me know??

EDIT: i have tried below suggestion as ,

package com.genedevelopers.shootthedevil;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.IBinder;

public class Devil {

    // This are starting data.
    public static final float initSpeed = 5;
    public static final long initTimeBetweenDucks = 1800; // in milliseconds

    public static Context dctx;
    private boolean mIsBound = false;

    // This is current speed that will be increased and current time that will be decreased.
    public static float speed;
    public static long timeBetweenDucks; // in milliseconds

    public static long timeOfLastDuck;

    public static boolean direction = true;

    // Needed for speeding up the game
    public static long timeBetweenSpeedups = 250; // in milliseconds
    public static long timeOfLastSpeedup;


    // Devil position on the screen.
    public float x;
    public float y;

    // Speed and direction.
    private float velocity;

    //MusicService musicS;

    //For background Music start
    private MusicService2 mServ;
    private ServiceConnection Scon =new ServiceConnection(){

        public void onServiceConnected(ComponentName name, IBinder
                binder) {

            mServ = ((MusicService2.ServiceBinder)binder).getService();
        }

        public void onServiceDisconnected(ComponentName name) {
            mServ = null;
        }
    };

    void doBindService(){

        dctx.bindService(new Intent(dctx,MusicService2.class),
                Scon, Context.BIND_AUTO_CREATE);

        mIsBound = true;
    }

    void doUnbindService()
    {
        if(mIsBound)
        {
            dctx.unbindService(Scon);
            mIsBound = false;
        }
    }
    //For background Music end

    public Devil(int y){
        this.y = y;

        if(Devil.direction){
            this.x = Game.screenWidth;
            velocity = speed * -1;
        } else {
            this.x = 0 - Game.duckImage.getWidth();
            velocity = speed;
        }

        doBindService();
        // We change direction for a next devil.
        Devil.direction = !Devil.direction;
        dctx=HighScore.ctx;

    }


    /**
     * Move the devil.
     */
    public void update(){
        this.x += velocity;
    }

    /**
     * Draw the devil to a screen.
     * 
     * @param canvas Canvas to draw on.
     */
    public void draw(Canvas canvas){

   //     musicS=new MainMenu().getMusicServiceInstance();

        if(velocity < 0)
            canvas.drawBitmap(Game.devilImage, x, y, null);
        else
            canvas.drawBitmap(Game.devilRightImage, x, y, null);
    }


    /**
     * Checks if the devil was touched/shoot.
     * 
     * @param touchX X coordinate of the touch.
     * @param touchY Y coordinate of the touch.
     * 
     * @return True if touch coordinates are in the coordinates of devil rectangle, false otherwise.
     */
    public boolean wasItShoot(int touchX, int touchY){
        Rect devilRect = new Rect((int)this.x, (int)this.y, (int)this.x + Game.devilImage.getWidth(), (int)this.y + Game.devilImage.getHeight());



        if(duckRect.equals(true)){
            Intent music = new Intent();
            music.setClass(dctx,MusicService2.class);
            dctx.startService(music);
        }
        return duckRect.contains(touchX, touchY);
    }

}

but it is not working please help me...

kumar
  • 708
  • 4
  • 15
  • 39

4 Answers4

0

In theory you can, but you need the Context to start a service. The Context usually is an Activity or a Service (What is 'Context' on Android?). You can pass a reference of Context to the utility class and start the service from there.

Community
  • 1
  • 1
solosodium
  • 11
  • 2
0

startService is a method of Context not Activity. As long as you have a context you can start service using it.

You can do as follows:

public class MyApp extends Application {
  public static MyApp instance;
   public void onCreate() {
     super.onCreate()
     instance = this;
   }
}

Then from any place you can do MyApp.instance.startService(...).

If you do so make sure you register your app class in the manifest.

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
0

you can start it if you pass the context to the class (e.g. in constructor)

context.startService(intent)) 
juankirr
  • 323
  • 2
  • 13
0

Hi thanku you all for ur replay...its working now...simple mistake if(duckRect.equals(true)){ } was never true so it was notcaling the service.

kumar
  • 708
  • 4
  • 15
  • 39