如何使用应用程序类来启动服务并在我的活动中使用它?

时间:2017-07-21 09:24:46

标签: java android

我有一个服务,两个活动和一个扩展的应用程序。 所以我担心的是,如果我在一个活动中实现该应用程序,那么在切换到下一个活动后它就会丢失。我的想法是在我的应用程序类的帮助下在这两个活动中使用服务对象。那么我如何实现它以在我的两个活动中拥有相同的应用程序类?

public class AppController extends Application {
boolean bound = false;
private static AppController mInstance;

private LocalService mBoundService;

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mBoundService = ((LocalService.LocalBinder) service).getService();
        System.out.println("Connected!!!!");
        bound = true;
    }

    public void onServiceDisconnected(ComponentName className) {
        mBoundService = null;
        bound = false;
    }
};


public static synchronized AppController getInstance() {
    return mInstance;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
}
public void startService(){
    //start your service

}
public void stopService(){
    //stop service
}
public LocalService getService(){
    return mBoundService;
}
}

1 个答案:

答案 0 :(得分:0)

答案是在像这样的应用程序类中实现它

public class AppController extends Application {
boolean bound = false;
private static AppController mInstance;

private LocalService mBoundService;

/**
 * The Background Service, which is started to communicate with multiple activities
 */
private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mBoundService = ((LocalService.LocalBinder) service).getService();
        System.out.println("Connected!!!!");
        bound = true;
    }

    public void onServiceDisconnected(ComponentName className) {
        mBoundService = null;
        bound = false;
    }
};


public static synchronized AppController getInstance() {
    return mInstance;
}


/**
 * With the start of app controller, the Service starts too
 */
public void onCreate() {
    startService(new Intent(this, LocalService.class));
    doBindService();
    super.onCreate();
}
public void startService(){

}
void doBindService() {
    bindService(new Intent(this,
            LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
}

public void stopService(){
    //stop service
}
public LocalService getService(){
    return mBoundService;
}
public void test(){
    System.out.println("Test");
}
}

使用BroadCastReceiver,您可以与活动进行通信。