需要后台运行过程

时间:2011-09-02 07:30:56

标签: android

实际上我已经使用两个IP地址从设备中安装的应用程序中编写了一个使用webservice来更新服务器数据库的方法。如果一个IP失败,那么它会使用第二个IP来提升服务器上的数据。 如果IP地址都失败,我将数据保存到我的sqllite数据库表tblTransaction之一。下面给出了代码。

private void Delay15Minute() throws IOException {
        String server1IPAddress = "";
        String server2IPAddress = "";
        String deviceId = "";
        Cursor cursorAdmin;
        Cursor cursorTransaction;
        adminhelper = new admin_helper(this);
        cursorAdmin = adminhelper.GetAdminDetails();
        if (cursorAdmin.moveToFirst())
            server1IPAddress = cursorAdmin.getString(cursorAdmin
                    .getColumnIndex("RemoteServer1IPAddress"));
        server2IPAddress = cursorAdmin.getString(cursorAdmin
                .getColumnIndex("RemoteServer2IPAddress"));
        deviceId = cursorAdmin.getString(cursorAdmin
                .getColumnIndex("DeviceID"));
        cursorAdmin.close();




        ContentValues initialDelay15 = new ContentValues();
        ContentValues initialTransaction = new ContentValues();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
        String RevisedEstimatedDate = sdf.format(date);



        manifest_helper = new manifest_helper(this);
        cursor = manifest_helper.GetDeliveries(pkManifest);
        cursor.moveToFirst();
         dbAdapter = new DatabaseAdapter(this); 
         dbAdapter.open();

        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.getString(cursor.getColumnIndex("PKDelivery"));
            String RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));     

            // get hour and minute from time string
            StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
            int j = 0;
            int[] val = new int[st1.countTokens()];
            // iterate through tokens
            while (st1.hasMoreTokens()) {
                val[j] = Integer.parseInt(st1.nextToken());
                j++;
            }

            // call time add method with current hour, minute and minutesToAdd,
            // return added time as a string
            String dateRevisedEstimatedDeliveryTime = addTime(val[0], val[1], 15);
            initialDelay15.put("RevisedEstimatedDeliveryTime",
                    dateRevisedEstimatedDeliveryTime);


             dbAdapter.UpdateRecord("tblDelivery", initialDelay15, "PKDelivery"
             + "=" + cursor.getString(cursor.getColumnIndex("PKDelivery")), null);


        }
        dbAdapter.close();
        dataXmlExporter=new DataXmlExporter(this);
        dataXmlExporter.StartDataSet();     
        cursor = manifest_helper.GetDeliveries(pkManifest);
        dataXmlExporter.AddRowandColumns(cursor,"tblDelivery");

        String sqlTransaction = "Select 6 as TransactionType,'Update Revised Estimated Delivery Time' as Description,"
                + " deviceId as DeviceID ,date() as TransactionUploadDate,time() as TransactionUploadTime from tblAdmin where PKAdmin > ?";

        dbAdapter = new DatabaseAdapter(this); 
        dbAdapter.open();
        cursorTransaction = dbAdapter.ExecuteRawQuery(sqlTransaction, "-1");
        dataXmlExporter.AddRowandColumns(cursorTransaction, "Transaction");



        String XMLTransactionData=dataXmlExporter.EndDataSet();     

        try {

            if ((server1IPAddress != "") && (server2IPAddress != "")) {
                try {
                    if (server1IPAddress != "") {
                        InsertUploadedTrancasctionDetails(server1IPAddress,
                                deviceId, XMLTransactionData);
                    }
                } catch (Exception exception) {

                    if ((server1IPAddress != server2IPAddress)
                            && (server2IPAddress != "")) {
                        InsertUploadedTrancasctionDetails(server2IPAddress,
                                deviceId, XMLTransactionData);
                    }
                }

            }
        } catch (Exception exception) {

            initialTransaction.put("ReceivedDate",
                    RevisedEstimatedDate);
            initialTransaction.put("TransactionData",
                    XMLTransactionData);            
            dbAdapter.InsertRecord("tblTransaction", "",
                    initialTransaction);



        } 
        dbAdapter.close();

        LoadDeliveries(pkManifest);
    }

问题是,当我们连接到运行的应用程序时,我需要自动将数据更新到存储在tbltransaction中的服务器。我认为可以通过建立backround运行过程和我的将检查tbltransaction中是否有数据以及与服务器的连接的应用程序。

任何人都会对此有所了解......如果是这样,请帮助meee ............

1 个答案:

答案 0 :(得分:0)

以下是一些方法,它们将共同做到这一点。这些都在服务中,您可以使用Handler代替并在活动中执行此操作,但服务是更明智的选择。

首先,我们需要能够判断我们是否在线,这需要网络状态和Wifi状态权限:

public boolean isOnline() {
    try {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo().isConnectedOrConnecting();
    } catch (Exception e) {
        return false;
    }
}

接下来,我们需要设置警报才能重试。添加这些变量:

private static AlarmManager am;
private static PendingIntent pIntent;
public static final int MSG_UPDATE = 0;
public static final String PENDING_REQ_KEY = "request";

并设置警报方法:

private synchronized void setAlarm() {

    if (am == null) am = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 
    if (Constants.LOG_DEBUG) Log.d(TAG,"Setting Alarm for 5 mins");
    long delay = 300000L; //5 Mins
    Intent i = new Intent(this,Service.class); //Reference the Service this method is in
    i.putExtra(PENDING_REQ_KEY, MSG_UPDATE);
    pIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    am.set(AlarmManager.RTC,System.currentTimeMillis()+delay,pIntent);

}

接下来,覆盖onStartCommand方法,以捕获更新请求:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent.getExtras() != null && intent.getExtras().containsKey(PENDING_REQ_KEY)) {
        int request = intent.getExtras().getInt(PENDING_REQ_KEY);
        if (request == MSG_UPDATE) update();
    }
    return START_STICKY;
}

最后,你的更新方法:

public void update() {
    if (isOnline()) {
        /** Push data to server here */
    }
    else {
        setAlarm();
    }
}