我正在运行一个只有一个活动的应用程序,并在
清单:
停止客户端:
onStart
中调用startService(new Intent(this,TCPClient.class));
。此外,我在服务的onCreate()
中启动线程,以建立与我的服务器的TCP连接。服务在单独的进程中运行。它工作得很好,直到我重新启动应用程序(当应用程序关闭时,我不会停止服务)。这样做后,我会从同一IP地址获得1个以上的连接。因此,我有两个客户端连接到同一设备和同一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;
}
停止客户端:
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;
}