如何在Android应用程序和Web服务之间的通信期间管理连接丢失?

时间:2013-04-02 09:15:21

标签: java android web-services

我正在研究与web服务通信的android项目,以便接收数据并将它们存储到数据库中。

在发送操作之前,我验证连接状态(参见下面的代码)

if (XXX.getInstance(Context).isOnline(Context)) 
{
//TODO Sending operation
}

但是在此操作期间,如果设备处于脱机状态,我会丢失数据,尽管HTTP状态代码为200或201.

我在操作前进行管理,但未在此期间进行管理。

  

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用广播接收器不断检查连接状态。

首先使用onCreate()方法注册接收器:

registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

然后在发现所需信号时写下您想要做的事情:

private BroadcastReceiver mReceiver = new BroadcastReceiver()
{
    public void onReceive(Context context, Intent intent)
    {
        cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnected()) 
        {
        //You are still connected
        }
        else
        {
        //You have lost connection
        }
    }
};

确保在离开活动后(在onDestroy())方法中取消注册接收器:

if (mReceiver != null)
{
    unregisterReceiver(mReceiver);
}