Android服务:如何启动服务

时间:2011-11-24 07:02:12

标签: android service

我的要求是:

我想将sqlite表记录上传到MS SQL server.I有service.Normal上传alos工作正常(正常上传意味着登录后,会显示上传表信息列表。当用户点击上传按钮时,上传&转到下一个屏幕)。现在我想这样做:销售代表保存发票/付款然后服务开始&在后端sql server中上传数据而不影响其余的代码。

我确实喜欢这个:

    public class UploadService extends Service {
  private static final String TAG = "UploadService";
  public static final String APPURL = "http://192.168.1.213:7986/XontService";
  private static final String NAMESPACE = "http://tempuri.org/";
  private static final String METHOD_NAME = "convertJSONToDataSet";
  private static String SOAP_ACTION = "http://tempuri.org/IXontService/convertJSONToDataSet";
  ArrayList<String> uploadFiler = new ArrayList<String>();  
  HashMap<Integer,String> uploadTable = new HashMap<Integer, String>();

  @Override
  public IBinder onBind(Intent arg0) {
    return null;
  }

  @Override
  public void onCreate() {
    Toast.makeText(this, "Upload Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");
    uploadUsingService();

  }

  @Override
  public void onDestroy() {
    Toast.makeText(this, "Upload Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
  }

  @Override
  public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "Upload Service Started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");

  }


  public void uploadUsingService(){
    uploadTable = getUploadTable();
    if(uploadTable.size() > 0){
      for (Map.Entry<Integer, String> entry : uploadTable.entrySet()) {
        System.out.println("----key" + entry.getKey());
         String value = entry.getValue();

         if(value.equals("WMInvoiceHeader")){
           getInvoiceHeader();
         }
      }
    }
  }

  public void getInvoiceHeader(){
    boolean serviceStatus =true;
    DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
    //  dbAdapter.openDataBase();

     SharedPreferences myPrefs = this.getSharedPreferences("myLogedPrefs",MODE_PRIVATE);
      String  strBusinessUnit = myPrefs.getString("BusinessUnit", "");
      String  strExecutive = myPrefs.getString("Executive", "");

      try{
        StringBuffer invoiceHeader = new StringBuffer();
      JSONArray jaHeader = new JSONArray();
      String query = "SELECT BusinessUnit,ExecutiveCode,InvoiceNo,SalesCategory,RetailerCode," +//4
              " RetailerCodeSon,InvoiceDate,GrossValue,InvoiceValue,TotalLineDiscount," + //9
              " TotalHeaderDiscount,VATValue,UpdatedOn,UpdatedBy,UploadFlag,VisitNumber ," + //15
              " VisitSequence,RouteCode,SalesType,ActiveStatus,UploadedOn,UploadedBy,UploadedMethod," +
              " UploadedType,RetailerType,HeaderDiscountFlag,SpecialDiscountFlag,TXNReference,TourReference" +
              " FROM WMInvoiceHeader " +
              " WHERE (CancelFlag IS NULL OR CancelFlag ='0')";
         ArrayList<?> stringList = dbAdapter.selectRecordsFromDBList(query, null);
       if(stringList.size() > 0){
        invoiceHeader.append("{\"WMInvoiceHeader\":");
           for (int i = 0; i < stringList.size(); i++) {
             ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
             ArrayList<?> list = arrayList;
             JSONObject invHeader = new JSONObject();
             invHeader.put("BusinessUnit",(String)list.get(0));
             invHeader.put("ExecutiveCode",(String)list.get(1));
             invHeader.put("InvoiceDate",(String)list.get(6));
             invHeader.put("VisitSequence",(String)list.get(16));
             invHeader.put("RouteCode",(String)list.get(17));
             invHeader.put("SalesType",(String)list.get(18));         
           jaHeader.put(invHeader);
           }
       }
      invoiceHeader.append(jaHeader.toString());
      invoiceHeader.append("}");
      serviceStatus = soapPrimitiveData("WMInvoiceHeader", strBusinessUnit, strExecutive, invoiceHeader.toString());

        }catch (IOException e) {
        serviceStatus =false;
        e.printStackTrace();
      } catch (XmlPullParserException e) {
        serviceStatus =false;
        e.printStackTrace();
      }catch (Exception e) {
        serviceStatus =false;
        e.printStackTrace();
      }finally{
        if(!serviceStatus){
          uploadFiler.add("WMInvoiceHeader");
        }
      }


  }

  public boolean soapPrimitiveData(String tablename,String strBusinessUnit, String strExecutive,String jsonString) throws IOException,XmlPullParserException {
    SoapPrimitive responsesData = null;
    boolean status =false;
    SoapObject requestData = new SoapObject(NAMESPACE, METHOD_NAME); // set
    requestData.addProperty("strBusinessUnit", strBusinessUnit);
    requestData.addProperty("strExecutiveCode", strExecutive);
    requestData.addProperty("strTableName", tablename);
    requestData.addProperty("jsonContent", jsonString);
    SoapSerializationEnvelope envelopes = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap//// envelope
    envelopes.dotNet = true;
    envelopes.setOutputSoapObject(requestData);
    AndroidHttpTransport httpTransport = new AndroidHttpTransport(APPURL);
    httpTransport.debug = true;
    try {
      httpTransport.call(SOAP_ACTION, envelopes);
      responsesData = (SoapPrimitive) envelopes.getResponse();
      if((responsesData.toString()).equals("true")){
        DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(UploadService.this);
         status = dbAdapter.updateUploadedTable(tablename, strExecutive, strBusinessUnit);
      }


    } catch (SocketException ex) {
      status = false;
      Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
      ex.printStackTrace();
    } catch (Exception e) {
      status = false;
      Log.e("Error : " , "Error on soapPrimitiveData() " + e.getMessage());
       e.printStackTrace();
      }
    return status;
  }


  public HashMap<Integer,String> getUploadTable(){
    DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
       dbAdapter.openDataBase();

      SharedPreferences myPrefs = this.getSharedPreferences("myLogedPrefs",MODE_PRIVATE);
    String  strBusinessUnit = myPrefs.getString("BusinessUnit", "");
    String  strExecutive = myPrefs.getString("Executive", "");


       HashMap<Integer,String> uploadTableMap = new HashMap<Integer,String>();
       try {
         String query = "SELECT TableName FROM WMPalmUploadControl WHERE Upload = '1' AND BusinessUnit =? AND ExecutiveCode = ?;";
         String[] d = new String[]{strBusinessUnit,strExecutive};
         ArrayList<?> stringList = dbAdapter.selectRecordsFromDBList(query, d);
       if(stringList.size() > 0){
           for (int i = 0; i < stringList.size(); i++) {
             ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
             ArrayList<?> list = arrayList;
             uploadTableMap.put(i, (String)list.get(0));
           }

       }
       dbAdapter.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

    return uploadTableMap;
  }

}

我想在uploadUsingService()中调用onStart()方法。

这是我的主叫代码:

   if(is3g ||isWifi){
            startService(new Intent(this, UploadService.class));
    }else if (networkType == TelephonyManager.NETWORK_TYPE_GPRS) {
            if(signalStrengthInt > 10){  ....}

    }  

当我运行此代码时:我得到了这个onCreate()' method Toast message上传服务创建. ' onStart()`Toast消息不显示。我怎么称呼这个。我从这个Link

做了这部分

请有人帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:6)

自Android 2.0以来,service.onStart已被弃用。也许在您使用的版本中不再调用它。阅读:http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html

请改用service.onStartCommand。