gpt4 book ai didi

独立进程中的 Android 服务

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:50 30 4
gpt4 key购买 nike

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

list :

<?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>

开始时:

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

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

启动命令:

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;
}

最佳答案

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

打开进程 View (例如 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() 中放置一个断点,看看那里会发生什么。

关于独立进程中的 Android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896573/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com