服务多次启动时会发生什么

时间:2012-02-15 17:25:50

标签: android service android-service

我创建了一个简单的服务,它会增加一个计数器并记录它。

    public class AudioService extends Service {
    int i=0;
    private final IAudioInterface.Stub mBinder = new IAudioInterface.Stub() {

            public int getI()
            {
                return i;
            }

        };

        @Override
        public IBinder onBind(Intent intent) {

            Log.d("onBind from service","****");

            return mBinder;
        }

        @Override
        public void onCreate() {

            super.onCreate();
            Log.d("onCreate from service","***");
            Log.d("i=","="+i);
            i=i+1;


        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d("OnDestroy Called from service","***");


        }

        public void onStartCommand(Intent intent, int startId) {
            super.onStart(intent, startId); 
            Log.d("onStartCommand from service","***");

        }

        @Override
        public boolean onUnbind(Intent intent) {
            Log.d("onUnbind from service","***");
        return super.onUnbind(intent);
        }

我正在递增他服务的oncreate方法中的i值。

客户活动如下所示

 public class AidlInterfaceServiceActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */

private static final String TAG = "Audio:Service";
IAudioInterface mService = null;
boolean connected = false;
ServiceConnection mConnection  = new ServiceConnection(){

    public void onServiceConnected(ComponentName arg0, IBinder service) {
        // TODO Auto-generated method stub
        connected = true;
        Log.d("Service connected","**");
        mService = IAudioInterface.Stub.asInterface(service);

        try {
            Log.d("i from client","="+mService.getI());
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void onServiceDisconnected(ComponentName arg0) {
        // TODO Auto-generated method stub
        Log.i(TAG, "Service disConnected");
        connected = false;
        mService= null;
    }
 };


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Log.d("on created ","**********");

    Intent music = new Intent();
    music.setClass(this,AudioService.class);
    startService(music);
    bindService(music, mConnection, Context.BIND_AUTO_CREATE);


}

AIDL文件如下

interface IAudioInterface
{

    int getI();
}

问题是每当i的值为“0”时我运行客户端活动。 我的价值没有增加。

我有这些疑问 1.服务多次启动时会发生什么 2.当服务多次受限时会发生什么 3.多次启动时,服务类中的数据成员会发生什么。这些数据成员是否重新初始化。

我真的很困惑。任何人请帮忙。

1 个答案:

答案 0 :(得分:0)

如果将计数器变量声明为静态会有帮助吗?