开发者

Need background running process

开发者 https://www.devze.com 2023-04-01 06:38 出处:网络
Actually I have written a method for updatiing server database using webservice from my application installed in the device using two IP Address.If one IP failed then it usess the second IP for upadti

Actually I have written a method for updatiing server database using webservice from my application installed in the device using two IP Address.If one IP failed then it usess the second IP for upadting the data at server. If Both the IP address failed i am saving the data to one of my sqllite database table tblTransaction.The code for that is given below.

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);
    }

The Problem is that i need to update the data to the server that stored in the tbltransaction automatically when we get connection to the serverIP along with my running application.I think it is possible by means of establishing backround running process along with my application that will check whethere data is there in the tbltransaction and connection with server is there.

So will any one have an idea for this ...if so please help meee...........


Here are a couple of methods that together will do just this. This is all within a Service, you could use a Handler instead and do this within an activity, but a Service is a wiser choice.

First, we need to be able to tell if we're online, this requires Network State and Wifi State Permissions:

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

Next we need to be able to set an alarm to retry. Add these variables:

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

And a set alarm method:

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);

}

Next, Override the onStartCommand method, to capture the update request:

@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;
}

finally, your update method:

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

精彩评论

暂无评论...
验证码 换一张
取 消