为什么服务会在一段时间后自动停止(大约每10-15分钟)

时间:2012-01-16 09:00:30

标签: android

我已经创建了服务并且该服务在重启设备时启动但有一段时间它会自动停止,因为我必须每隔10-15分钟重新启动设备。我希望我的服务继续在后台运行,直到我关闭设备。请帮助。我的代码:

Socketreceiver.java

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, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><whizpay><IntermdMsg><ResponseCode>00</ResponseCode><ResponseMsg>Void Response</ResponseMsg></IntermdMsg></whizpay>");


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

            }
        }
    };

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

}

的AndroidManifest.xml

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

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

SocketreceiverService.java

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 & 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<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("<ResponseCode>99</ResponseCode>");
                int index2=response.indexOf("<ResponseCode>98</ResponseCode>");
                if(index>0||index1>0||index2>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 && one is Registration request..
    // for payment BT should be called and add this BT to original xml & 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("<Level1>");
        if(stindex>0){          //this is payment request. So start Bluetooth
            Logger.writeLOG(tag," return true");
            return true;
        }else
        {
            stindex = tempdatareceived.indexOf("<CustomerInformation>");
            if(stindex>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 = "</Level1><Level2></Level2><Level3></Level3></whizpay>";
      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("<Level1>");
        if(stindex>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("</Level1>");
        String neworgString = dataRecived.substring(stindex, endindex); // data between <wizpay> </wizpay> tag
        Log.d(tag,"data between levl1 tag==" + neworgString);
        newxmlData += neworgString;
        //newxmlData += "<Track1DataEncrypted>" + BluetoothResponse + "</Track1DataEncrypted>";
        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);
    }
}

请帮忙。 感谢。

1 个答案:

答案 0 :(得分:1)

如果您希望Android尽可能长时间保持您的服务,您需要使用startForeground()方法。但是你应该问问自己,你是否真的需要它运行一段时间。你很有可能不需要它。