Android服务在单独的过程中

我正在使用单个活动运行我的应用程序并调用startService(new Intent(this,TCPClient.class));在onStart.我也在onCreate()服务中启动线程,设置与我的服务器的TCP连接.服务在单独的进程中运行.它一直运行良好,直到我重新启动我的应用程序(我不会在应用程序关闭时停止服务).当我这样做时,我将从同一IP获得1个以上的连接.所以,我有2个客户端从同一设备和相同的IP连接.问题是:如何防止创建更多服务?

表现:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sample.servicetest" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/MainActivityTheme" >
        <!-- android:theme="@style/AppTheme" > -->
        <service android:name=".TCPClient"
            android:process=":service">
        </service>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/MainActivityTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

的OnStart:

@Override
    protected void onStart() {
        super.onStart();

        Log.v(TAG, "onStart");
        startService(new Intent(this, TCPClient.class));
    }

onStartCommand:

public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                if (bundle.containsKey("stop"))
                {
                    stopClient();
                }
            }
        }
        Log.v(TAG, "onStartCommand...");
        return TCPClient.START_STICKY;
    }

stopClient:

private void stopClient() {

        // send mesage that we are closing the connection
        sendCmd(CLOSED_CONNECTION);

        mRun = false;

        SharedPreferences prefSettings = getSharedPreferences("settings", MODE_PRIVATE);
        Editor settingsEd = prefSettings.edit();
        settingsEd.putInt("connected", 0);
        settingsEd.apply();

        if (mBufferOut != null) {
            mBufferOut.flush();
            mBufferOut.close();
        }

        mBufferIn = null;
        mBufferOut = null;
        mServerMessage = null;
    }

When I do that, new process with service is created.

打开流程视图(例如DDMS透视图 – >设备)并检查启动的服务数量.我打赌只会有一个.

So, I have 2 client connected from same device and same IP. Question is: How to prevent creating more services?

我怀疑你需要检查服务中的连接/断开逻辑,因为Android只允许启动一个服务实例.当服务启动时,onCreate()被调用.以下所有startService()命令都进入服务的onStartCommand()方法.只需在服务onCreate()和onStartCommand()中加入一个断点,看看那里发生了什么.

相关文章
相关标签/搜索