当活动退出并解除绑定时我的服务关闭,希望它继续运行

时间:2018-02-23 15:58:10

标签: android

我正在尝试创建一个bacckground服务,该服务将有一个每分钟向计数器添加一个的线程。 我希望其他应用程序能够调用一个会调用该值的methed调用getBot。

现在我有一个测试应用程序,它具有绑定到应用程序的激活,因此它可以与它通信以获取计数器。当它退出时它就会解开它。 它有一个名为botGert的按钮,它从服务中获取当前的计数器值。

当它解开它时,服务就会关闭。我怎么能得到它所以它不会关闭????

服务类 公共类MessengerService扩展了服务{

/** Command to the service to display a message */
static final int MSG_SAY_HELLO = 1;
static final int MSG_BOT_GET = 2;
static final int MSG_BOT_SET = 3;
static final int MSG_BOT_STOP = 4;
static final int MSG_BOT_PAUSE = 5;
static final int MSG_GET_ORDERS = 6;
static final int MSG_GET_POINT = 7;

static final int MSG_BOT_GET_RES = 2;

static final int PRICE_STATIC =1;
static final int PRICE_PERCENTAGE =2;
static final int PRICE_ALL = 3;

static final int VOL_STATIC = 1;
static final int  VOL_PERCENTAGE = 2;
static final int  VOL_ALL = 3;

int counter;

boolean isStop=false; // put bot in pause ste on next 1 min update
boolean isUYpdateNextMinute=false;
/**
 This is called by a client to exicute code in this service
 */
class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_BOT_GET:
                Message resp = Message.obtain(null, MSG_BOT_GET_RES);
                Bundle bResp = new Bundle();
                bResp.putString("respData", Integer.toString(counter ));
                resp.setData(bResp);
                try {
                    msg.replyTo.send(resp);
                } catch (Exception e)
                {

                }

                Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                break;
             default:
                super.handleMessage(msg);
        }
    }
}

final Messenger mMessenger = new Messenger(new IncomingHandler());

/**
 * When binding to the service, we return an interface to our messenger
 * for sending messages to the service.
 */
@Override
public IBinder onBind(Intent intent) {
    Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
    return mMessenger.getBinder();
}


//////////////////////////////////////////////////////////////////////////////
// emplanent callbacks

MessengerService parent;
@Override
public void onCreate() {
    Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
    parent=this;

}
@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    ThreadDemo T1 = new ThreadDemo( "Thread-1");
    T1.start();

// sgart 1分钟更新帖子

}
@Override
public void onDestroy() {
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();

}

/////////////////////////////////////////////// //////////////// //运行计数器的线程代码

类ThreadDemo扩展了线程{

private String threadName;

ThreadDemo( String name) {
    threadName = name;
    System.out.println("Creating " +  threadName );
}

public void run() {
    try {
        do {
            counter++;
            Thread.sleep(1000 *60 );
            counter++;
        } while (true);
    } catch(Exception e)
    {
        Toast.makeText(parent, "thread stopped", Toast.LENGTH_LONG).show();
    }
} // end inner thread class

} //结束课

}

/////////////////////////////////////////////// ////////////////////// 活动类

公共类ActivityBoundMessenger扩展了AppCompatActivity {

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

/** Messenger for communicating with the service. */
Messenger mService = null;

/** Flag indicating whether we have called bind on the service. */
boolean mBound;

/**
 * Class for interacting with the main interface of the service.
 */

/////////////////////////////////////////////////////////////////////////////////////////
private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the object we can use to
        // interact with the service.  We are communicating with the
        // service using a Messenger, so here we get a client-side
        // representation of that from the raw IBinder object.
        mService = new Messenger(service);
        mBound = true;
    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        mService = null;
        mBound = false;
    }
};

/////////////////////////////////////////////// /////////////////////////////////

public void sayHello(View v) {
    if (!mBound) return;
    // Create and send a message to the service, using a supported 'what' value
    Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
    try {
        mService.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}


public void butSet(View v) {
    if (!mBound) return;
    // Create and send a message to the service, using a supported 'what' value
    Message msg = Message.obtain(null, MessengerService.MSG_BOT_SET, 0, 0);
    Bundle b = new Bundle();
    b.putString("data", "json object");
    msg.setData(b);

    try {
        mService.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

public void butGet(View v) {
    if (!mBound) return;
    // Create and send a message to the service, using a supported 'what' value

    Message msg = Message
            .obtain(null, MessengerService.MSG_BOT_GET);

    msg.replyTo = new Messenger(new ResponseHandler());
    // We pass the value

    try {
        mService.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}



////////////////////////////////////////////////////////////////////////////////////////
// these metheds get called whenb this acty starts and endsa
@Override
protected void onStart() {
    super.onStart();

    // Bind to the service
////////////////////////////////////////////
    Intent ser = new Intent(this, MessengerService.class);
    startService(ser);
    bindService(ser, mConnection,
            Context.BIND_AUTO_CREATE);
///////////////////////////////////////////

}

@Override
protected void onStop() {
    super.onStop();
    // Unbind from the service
    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
}



// This class handles the Service response
int ted=0;
String nextUpdate=null;
class ResponseHandler extends Handler {

    @Override
    public void handleMessage(Message msg) {
        int respCode = msg.what;

        switch (respCode) {
            case MessengerService.MSG_BOT_GET_RES:
                String nextUpdate= msg.getData().getString("respData");
                ted++;
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

来自Android Documentation

  

当最后一个客户端从服务解除绑定时,系统会销毁该服务,除非该服务也是由startService()启动的。

因此,您所要做的就是在服务中的onCreate()方法中调用它:

startService(new Intent(this, MessengerService.class))

当然,请确保在完成服务后致电stopSelf()