Why service stops automatically after sometime( approx every 10-15minutes)
<p>I have created service and that service starts on reboot of device but some time it gets stopped automatically because of that i have to reboot the device in every 10-15mins.I want my service keeps on running in background until i switch off the device.Please help.here my code:</p>

<p>Socketreceiver.java</p>

<pre><code>package com.test.Socketreceiver;

import java.net.Socket;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;


public class Socketreceiver extends BroadcastReceiver {

    private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
    public static final int SERVERPORT = 8060;
    public static String tag = "Socketreceiver";
    public static boolean flgvoid = false;
    public static SerialportCommunication spComm = new SerialportCommunication();
    //static BluetoothAdapter mBluetoothAdapter;

    /** Called when the activity is first created. */

    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if (intent.getAction().equals(BOOT_COMPLETED_ACTION)) {
        Logger.createFile();
            Logger.writeLOG("start app..", "app started...........................");
            Intent myIntent = new Intent(context, SocketreceiverService.class);
            context.startService(myIntent);

            if(!flgvoid){
                spComm.initalizeCommand();
                Logger.writeLOG(tag, "initializing serialport");
            }

            SocketreceiverService.setUpdateListener(serverCompleted);

        }
    }

    public SocketreceiverListener serverCompleted = new SocketreceiverListener() {

        public void response(Socket s, String datareceived) {
            // TODO Auto-generated method stub
            Log.d(tag, "data=" + datareceived);

            if(datareceived.contains("void")){
                String originaldatareceived = datareceived;
                flgvoid = true;
                datareceived = originaldatareceived.replace("void", "");

                Logger.writeLOG(tag," response recived after replacing void ="+datareceived);
            }else
                flgvoid = false;

            Logger.writeLOG(tag," response recived ="+datareceived);
            boolean checkRequest = SocketreceiverService.checkXMLrequest(datareceived);
            //System.out.println("checkst="+checkRequest);
            //this is used to card swipe over serial port
        //  boolean checkRequest = false;
            if (checkRequest) {

                //stop prompting swipecard reader
                if(!flgvoid){

                    Logger.writeLOG(tag,"Initilizing the Swipe device");
                    //SerialportCommunication spComm = new SerialportCommunication();
                    spComm.setReciveddata(datareceived);
                    spComm.setCliebntsocket(s);
                    //spComm.initalizeCommand();
                    spComm.swipecardCommand();
                    //SocketreceiverService.sendtoClient(s, "service returns="+datareceived);
                }
                else
                {   Logger.writeLOG(tag,"sending intermediate data");
                    SocketreceiverService.sendtoClient(s, "&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?&gt;&lt;whizpay&gt;&lt;IntermdMsg&gt;&lt;ResponseCode&gt;00&lt;/ResponseCode&gt;&lt;ResponseMsg&gt;Void Response&lt;/ResponseMsg&gt;&lt;/IntermdMsg&gt;&lt;/whizpay&gt;");


                    SocketreceiverService.sendResponse(s, datareceived,"");
                    Logger.writeLOG(tag,"sending response");
                }
            }else{
                SocketreceiverService.sendTowizpay(s, datareceived);

            }
        }
    };

    /*public String addEncryptionTag(String data) {
        String dataTag = "&lt;EncryptedInfo&gt;&lt;EncryptionLevel&gt;3&lt;/EncryptionLevel&gt;&lt;EncryptedData&gt;"
                + data + "&lt;/EncryptedData&gt;&lt;/EncryptedInfo&gt;";
        return dataTag;
    }*/

}
</code></pre>

<p>AndroidManifest.xml</p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.Socketreceiver"
      android:versionCode="1"
      android:versionName="1.0"&gt;
    &lt;uses-sdk android:minSdkVersion="8" /&gt;
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"&gt;&lt;/uses-permission&gt;
    &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"&gt;&lt;/uses-permission&gt;
    &lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"&gt;&lt;/uses-permission&gt;
    &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
    &lt;uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /&gt;
    &lt;uses-permission android:name="android.permission.BLUETOOTH" /&gt;
    &lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
        &lt;activity android:name="com.test.Socketreceiver.Socketreceiver" android:label="@string/app_name"&gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;
                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;

        &lt;service android:name="com.test.Socketreceiver.SocketreceiverService" /&gt;
        &lt;receiver android:name="com.test.Socketreceiver.Socketreceiver" android:label="@string/app_name"&gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.BOOT_COMPLETED" /&gt;
                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
            &lt;/intent-filter&gt;
        &lt;/receiver&gt;
    &lt;/application&gt;
&lt;/manifest&gt;
</code></pre>

<p>SocketreceiverService.java </p>

<pre><code>package com.test.Socketreceiver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class SocketreceiverService extends Service {

    private static SocketreceiverListener serverLISTENER;
    final static String tag = "SocketreceiverService";
    private Thread serverThread;
    private ServerSocket serverSocket;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "whizpay Service Created", Toast.LENGTH_LONG).show();
        Logger.writeLOG(tag," whizpay Service Created");
        Log.d(tag, "onCreate");

    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "wizpay Service Stopped", Toast.LENGTH_LONG).show();
        Logger.writeLOG(tag," whizpay Service Stopped");
        Log.d(tag, "onDestroy");
        if (serverSocket != null) {
            try {
                serverSocket.close();
                stopServer();
                Logger.writeLOG(tag," server closed...");
            } catch (Exception e) {
                // TODO: handle exception
                Log.d(tag, "exception=" + e.getMessage());
                Logger.writeLOG(tag,"@ line 56 exception=" + e.getMessage());
            }
        }
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "wizpay Service Started", Toast.LENGTH_LONG).show();
        Logger.writeLOG(tag,"whizpay Service Started");
        Log.d(tag, "onStart");
        startServer();
        Logger.writeLOG(tag,"start serial port...Testing starts.....");
        Logger.writeLOG(tag,"start serial port...Testing  ends......");
    }

    private synchronized void startServer() {
        if (serverThread == null) {
            Toast.makeText(this, "Started server", Toast.LENGTH_LONG).show();
            Logger.writeLOG(tag , " Started server");
            serverThread = new Thread(thread);
            serverThread.start();
        }
        else
        {
            Logger.writeLOG(tag , " close current and open again");
            if(serverThread.isAlive())
            {
                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                        stopServer();
                        Logger.writeLOG(tag," server closed...");

                    } catch (Exception e) {
                        // TODO: handle exception
                        Log.d(tag, "exception=" + e.getMessage());
                        Logger.writeLOG(tag,"@ line 56 exception=" + e.getMessage());
                    }
                }
            }
            serverThread = new Thread(thread);
            serverThread.start();
            Logger.writeLOG(tag," server started again...");
        }
    }

    private synchronized void stopServer() {
        if (serverThread != null) {
            Logger.writeLOG(tag , " WhizPay Service Stoped");
            Thread t = serverThread;
            serverThread = null;
            t.interrupt();
            serverSocket =null;
        }

    }

    public void onStop(Intent intent, int startid) {
        Logger.writeLOG(tag , " WhizPay Service onStop");
        Log.d(tag, "onStop");
    }

    private Runnable thread = new Runnable() {

        public synchronized void run() {
            try {
                //Logger.writeLOG(tag ," Receiving starts ="+serverSocket);
                serverSocket = new ServerSocket(Socketreceiver.SERVERPORT);
                Logger.writeLOG(tag ," new socket ="+serverSocket);
                String data = "";
                Socket client=null;
                while (true) {
                     client= serverSocket.accept();
                    Log.d(tag, "S: Receiving...");
                    try {
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(client.getInputStream()));
                        String line = null;
                        line = in.readLine();
                        if(line!=null){
                            if (serverLISTENER != null) {
                                Log.d(tag, "Received..=" + line);
                                // String receivedData=""+abc;
                                data = line;
                                System.out.println("Received..data=" + data);
                                Logger.writeLOG(tag ," Received..= data" + data);
                                serverLISTENER.response(client, data);
                                break;
                            }
                        }
                    } catch (Exception e) {
                        // e.printStackTrace();
                        Log.d(tag, "123Exception=" + e.getMessage());
                        Logger.writeLOG(tag , " Exception@ 130 ="+e.getMessage());
                    }
                }
                Logger.writeLOG(tag ," starts server 1...");
                startServer();
                Logger.writeLOG(tag ," starts server 2...");
            } catch (IOException e) {
                Log.e(tag, "error==" + e.getMessage());
                Logger.writeLOG(tag , " Exception@ 136 ="+e.getMessage());
            }
        }
    };

    public static void setUpdateListener(SocketreceiverListener l) {
        serverLISTENER = l;
    }

    // if something went wrong in communication error code will be -1. 
    // send this error to client.
    // if error code  is 0 then get response from wizpay for that xml &amp; send response to client
    public static void senderrorResponse(Socket s, int errorCode,String errormessage) {
        // TODO Auto-generated method stub
        Logger.writeLOG(tag," sendResponse satrts error code="+errorCode);
        Logger.writeLOG(tag," sendResponse satrts error code="+errormessage);
        sendtoClient(s, errorCode+"#"+errormessage);
    }

    //This will add data received from bluetooth to data received on socket.
    // create new request. send to wizpay
    // send response back to client
    public static void sendResponse(Socket s, String dataFromclient,String dataFrombluetooth) {
        Log.i("test1 dataFrombluetooth=",dataFrombluetooth);
        Logger.writeLOG(tag, "test1 dataFrombluetooth="+dataFrombluetooth);
        Log.i("test1 dataFromclient=",dataFromclient);
        Logger.writeLOG(tag, "test1 dataFromclient="+dataFromclient);
        String wizpayResponse="";
        int indexBt = dataFrombluetooth.indexOf("EncryptedInfo");
        //Comment for whizpay
        if(indexBt&lt;0){ 

          if(Socketreceiver.flgvoid){
                //{
            String newwizpayRequest = createWhizpayXmlrequest(dataFromclient,dataFrombluetooth);
            //}
            //System.out.println("new wizpay request...="+newwizpayRequest);
            Logger.writeLOG(tag, "new whizpay request...="+newwizpayRequest);
            boolean ispayment = checkXMLrequest(newwizpayRequest);
            wizpayCommuniction wizpayrequest = new wizpayCommuniction();
            wizpayrequest.setXMLRequest(newwizpayRequest);
            wizpayrequest.setOtherData(ispayment);
            wizpayResponse = wizpayrequest.getResponsefromwizpay();
            }
          else{
            // something went wrong in Bluetooth communication
                // send error back
            wizpayResponse = dataFrombluetooth;
            Log.e(tag,"error in BT...="+wizpayResponse);
            Logger.writeLOG(tag, "error in BT...="+wizpayResponse);
          }
        }else{
        // TODO Auto-generated method stub
            //{
                String newwizpayRequest = createWhizpayXmlrequest(dataFromclient,dataFrombluetooth);
            //}
            //System.out.println("new wizpay request...="+newwizpayRequest);
            Logger.writeLOG(tag, "new whizpay request...="+newwizpayRequest);
            boolean ispayment = checkXMLrequest(newwizpayRequest);
            wizpayCommuniction wizpayrequest = new wizpayCommuniction();
            wizpayrequest.setXMLRequest(newwizpayRequest);
            wizpayrequest.setOtherData(ispayment);
            wizpayResponse = wizpayrequest.getResponsefromwizpay();

            wizpayResponse +=SerialportCommunication.accountNumber;

            Logger.writeLOG(tag, "wizpayResponse after appending accountnumber...="+wizpayResponse);

        }//Comment for whizpay 
        Log.d(tag, "sending to base send response="+wizpayResponse);
        Logger.writeLOG(tag, "sending to base send response="+wizpayResponse);
        sendtoClient(s,wizpayResponse);
    }

    public static void sendtoClient(Socket s,String response){
        try {
            Log.d(tag, "S Sending..starts ");
            Logger.writeLOG(tag, "S Sending to client..starts ");
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(s.getOutputStream())), true);
            // where you issue the commands
            out.println(response);
            Log.d(tag, "S Sending to client..ends");
            Logger.writeLOG(tag, "S Sending to client..end ");
        } catch (Exception e) {
            Log.e(tag, "C: Error", e);
        } finally {
            Log.e(tag, "finally starts");

            try {
                int index=response.indexOf("CustomerToken");
                int index1=response.indexOf("&lt;ResponseCode&gt;99&lt;/ResponseCode&gt;");
                int index2=response.indexOf("&lt;ResponseCode&gt;98&lt;/ResponseCode&gt;");
                if(index&gt;0||index1&gt;0||index2&gt;0)
                    s.close();
                System.out.println("closed server side.....");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    // there are 2 xml request one is payment &amp;&amp; one is Registration request..
    // for payment BT should be called and add this BT to original xml &amp; then send request to wizpay
    // for registration request should sent to whizpay directly
    //  for registration there is tag CustomerInformation return false
    // for payment there is tag  return true
    // for all other request returns false.. o this will forward request as it is to wizpay
    public static boolean checkXMLrequest(String tempdatareceived){
        Logger.writeLOG(tag," in checkXMLrequest starts ="+tempdatareceived);
        int stindex = tempdatareceived.indexOf("&lt;Level1&gt;");
        if(stindex&gt;0){          //this is payment request. So start Bluetooth
            Logger.writeLOG(tag," return true");
            return true;
        }else
        {
            stindex = tempdatareceived.indexOf("&lt;CustomerInformation&gt;");
            if(stindex&gt;0){      //this is registration request
                Logger.writeLOG(tag," return false 0");
                return false;
            }else{              // some other request
                Logger.writeLOG(tag," return false 1");
                return false;
            }
        }

    }

    //This will create new xml request..
    // data received on socket port + bluetoth data 
    public static String createWhizpayXmlrequest(String dataRecived,
      String BluetoothResponse) {
      String endofXML = "&lt;/Level1&gt;&lt;Level2&gt;&lt;/Level2&gt;&lt;Level3&gt;&lt;/Level3&gt;&lt;/whizpay&gt;";
      String newxmlData = ""; 

    /*if(Socketreceiver.flgvoid)
    {
        Logger.writeLOG(tag," in createWhizpayXmlrequest for void transaction");

        newxmlData = dataRecived;
        Logger.writeLOG(tag," in createWhizpayXmlrequest newxmlData::" + newxmlData);

        newxmlData += endofXML;
        Logger.writeLOG(tag," in createWhizpayXmlrequest newxmlData::" + newxmlData);

    }else{  */
        // if any thing before Level1 take it..
        int stindex = dataRecived.indexOf("&lt;Level1&gt;");
        if(stindex&gt;0)
        {
            newxmlData += dataRecived.substring(0,stindex);
        }
        // if any thing before Level1 take it..
        Logger.writeLOG(tag," in createWhizpayXmlrequest dataRecived="+dataRecived+"BluetoothResponse="+BluetoothResponse);
        Log.d(tag,"data b4 level1="+newxmlData);
        int endindex = dataRecived.indexOf("&lt;/Level1&gt;");
        String neworgString = dataRecived.substring(stindex, endindex); // data between &lt;wizpay&gt; &lt;/wizpay&gt; tag
        Log.d(tag,"data between levl1 tag==" + neworgString);
        newxmlData += neworgString;
        //newxmlData += "&lt;Track1DataEncrypted&gt;" + BluetoothResponse + "&lt;/Track1DataEncrypted&gt;";
        newxmlData += BluetoothResponse ;
        newxmlData += endofXML;
        Log.d(tag,"new xml request =" + newxmlData);
        Logger.writeLOG(tag," new xml request =" + newxmlData);
    //}
        return newxmlData;
    }

    public static void sendTowizpay(Socket s,String dataRecived){
        Logger.writeLOG(tag,"sendTowizpay starts ");
        String wizpayResponse="";
        boolean ispayment = checkXMLrequest(dataRecived);
        Logger.writeLOG(tag,"is payment="+ispayment);
        wizpayCommuniction wizpayrequest = new wizpayCommuniction();
        wizpayrequest.setXMLRequest(dataRecived);
        wizpayrequest.setOtherData(ispayment);
        wizpayResponse = wizpayrequest.getResponsefromwizpay();
        Logger.writeLOG(tag,"sendTowizpay ends="+wizpayResponse);
        sendtoClient(s, wizpayResponse);
    }
}
</code></pre>

<p>please help.
Thanks.</p>
