Ale*_*ide 4 android android-service
我跑我的一个活动,并呼叫应用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>
Run Code Online (Sandbox Code Playgroud)
的OnStart:
@Override
protected void onStart() {
super.onStart();
Log.v(TAG, "onStart");
startService(new Intent(this, TCPClient.class));
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,创建了带有服务的新流程.
打开流程视图(例如DDMS透视图 - >设备)并检查启动的服务数量.我打赌只会有一个.
所以,我有2个客户端从同一设备和相同的IP连接.问题是:如何防止创建更多服务?
我怀疑你需要检查服务中的连接/断开逻辑,因为Android只允许启动一个服务实例.当服务开始时onCreate()被调用.以下所有startService()命令都进入onStartCommand()服务方法.只需在服务中加入一个断点onCreate(),onStartCommand()然后看看那里发生了什么.
| 归档时间: |
|
| 查看次数: |
6745 次 |
| 最近记录: |