Android:从活动以外的Utility类启动服务

时间:2015-10-20 19:30:34

标签: android android-fragments android-intent android-activity

我知道服务可以从Activity开始,如下所示

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));
   }
}

因为startService()方法在Activity类中,我认为不可能从任何不扩展活动类的java类调用服务... 如果有任何方法我们可以从普通/公共类开始服务,请告诉我??

编辑:我已尝试过以下建议,

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);
    }

}

但它不起作用请帮助我......

4 个答案:

答案 0 :(得分:0)

理论上你可以,但你需要Context来启动服务。上下文通常是一个活动或服务(What is 'Context' on Android?)。您可以将Context的引用传递给实用程序类,并从那里启动服务。

答案 1 :(得分:0)

startService是一种Context而不是Activity的方法。只要您有上下文,就可以使用它开始服务。

您可以执行以下操作:

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

然后,您可以从任何地方MyApp.instance.startService(...)

如果这样做,请确保在清单中注册您的应用类。

答案 2 :(得分:0)

如果将上下文传递给类(例如在构造函数中)

,则可以启动它
context.startService(intent)) 

答案 3 :(得分:0)

非常感谢大家的重播...现在正在工作......如果(duckRect.equals(true)){}从来都不是真的那么简单错误,所以它没有对服务进行调整。