Android service in separate process -
i'm running application single activity , phone call startservice(new intent(this, tcpclient.class));
in onstart
. start thread in oncreate()
of service sets tcp connection server. service running in separate process. works until restart application (i not stop service when app closed). when that, i'm getting 1 more connection same ip. so, have 2 client connected same device , same ip. question is: how prevent creating more services?
manifest:
<?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..."); homecoming tcpclient.start_sticky; }
stopclient:
private void stopclient() { // send mesage closing 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 that, new process service created.
open process view (e.g. ddms perspective -> devices) , check how many services started. bet there one.
so, have 2 client connected same device , same ip. question is: how prevent creating more services?
i suspect need check connect/disconnect logic within service, because android allows 1 instance of service started. when service started oncreate()
gets called. next startservice()
commands come onstartcommand()
method of service. set break point service oncreate()
, onstartcommand()
, see happens there.
android android-service
No comments:
Post a Comment