Android 在emulator中断开网络连接时,后台服务停止,adb断开

Android 在emulator中断开网络连接时,后台服务停止,adb断开,android,service,background,image-uploading,Android,Service,Background,Image Uploading,我想创建一个后台服务,它将持续检查网络连接,如果网络连接可用,它将获取保存在数据库中的图像路径,并上传图像。 我想要的是,当上传图像时,如果由于网络问题或任何其他方式导致网络断开,应用程序应停止上传过程,并再次检查网络连接是否可用,直到找到连接并启动上传过程。 现在的问题是当上传开始时,如果在模拟器中使用F8断开网络连接,它将断开模拟器与ADB的连接,我无法检查发生了什么,当我再次将手机连接到网络并刷新时,ADB模拟器已连接,但后台服务停止。 这是我试过的代码 public class MySe

我想创建一个后台服务,它将持续检查网络连接,如果网络连接可用,它将获取保存在数据库中的图像路径,并上传图像。 我想要的是,当上传图像时,如果由于网络问题或任何其他方式导致网络断开,应用程序应停止上传过程,并再次检查网络连接是否可用,直到找到连接并启动上传过程。 现在的问题是当上传开始时,如果在模拟器中使用F8断开网络连接,它将断开模拟器与ADB的连接,我无法检查发生了什么,当我再次将手机连接到网络并刷新时,ADB模拟器已连接,但后台服务停止。
这是我试过的代码

public class MyService extends Service{

public static final String TAG = "MyService";
ConnectionDetector cd;
boolean isInternetPresent = false;
boolean uploadingdata = false;
Integer serverResponseCode = 0;
String[] sourceFileUri;
String date;
private static long TIMEOUT_IN_SECONDS = 120;
@Override
public IBinder onBind(Intent arg0) {

    return null;
}
private TimerTask Chcknet = new TimerTask(){

@SuppressLint("SimpleDateFormat")
@Override
public void run() {
        // TODO Auto-generated method stub
    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
     date = df.format(Calendar.getInstance().getTime());
         cd  = new ConnectionDetector(getApplicationContext());
         isInternetPresent = cd.isConnectingToInternet();
         Log.d(TAG,"Continously running: "+date);
         Looper.prepare();
         try {
         if(isInternetPresent )
         {
            if(!uploadingdata)
            {
                Log.d(TAG,"call fetchdata"+date);

                    fetchdata();

            }else{
                Log.d(TAG,"Already uplaoding data"+date);
            }

         }
         else{
            uploadingdata = false;
            Log.d(TAG,"NO Internet Connection");
         }
         } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         Looper.loop();
}   };

@SuppressLint("SimpleDateFormat")
public void onCreate()
{

    String filePath = Environment.getExternalStorageDirectory() + "/logcat.txt";
    try {
        Runtime.getRuntime().exec(new String[]{"logcat", "-f", filePath, "MyAppTAG:V", "*:S"});
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Timer timer = new Timer();
    timer.schedule(Chcknet,1000L,20*1000L);
    Log.d(TAG,"Fetchdata"+date);
}
@SuppressLint("SimpleDateFormat")
public int onStartCommand(Intent intent,int flag,int Startid)
{
    return START_STICKY;
}

private void fetchdata() 
{
    // TODO Auto-generated method stub
    TestDatabase test_db = new TestDatabase(this);
    SQLiteDatabase db = test_db.getWritableDatabase();

        Cursor cursor = db.rawQuery("Select url from test_data where upload_Status='NO'",null);
        cursor.getCount();
        Log.d("TAG","value in the cursor: "+cursor.getCount());
        sourceFileUri = new String[cursor.getCount()];
        int i=0;

        if(cursor.moveToFirst()){

        do{
            sourceFileUri[i] = cursor.getString(0);
            i++;
        }while(cursor.moveToNext());
        Log.d(TAG,"length of the uri string: "+sourceFileUri.length);
        }
        if(sourceFileUri.length>0)
        {
            new doFileUpload().execute(sourceFileUri);
        }
}
class doFileUpload extends AsyncTask<String,Void,Integer>
{
    NotificationManager notificationManager;
    Notification.Builder nmBuilder;

    String fileName;
    HttpURLConnection conn = null;
    DataOutputStream dos = null; 
    long startTime = new Date().getTime();
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary ;


    File sourceFile;
    String urlString = "http://192.168.1.8:82/UploadToServer.php";

    @SuppressLint("NewApi")
    @Override
    protected Integer doInBackground(String... params) {
        // TODO Auto-generated method stub
         Log.d(TAG,"In doFileUpload"+sourceFileUri);
         nmBuilder = new Notification.Builder(getApplicationContext())
            .setContentTitle("Uploading Files")
            .setContentText("Uploading in progress")
            .setSmallIcon(R.drawable.ic_launcher);
            Intent intt = new Intent(getApplicationContext(),MyService.class);
            PendingIntent pdint = PendingIntent.getActivity(getApplicationContext(),0,intt, PendingIntent.FLAG_UPDATE_CURRENT);
            nmBuilder.setContentIntent(pdint);
            notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0,nmBuilder.build());
         for(int i=0;i<sourceFileUri.length;i++)
            {
                fileName = sourceFileUri[i]; 
                sourceFile = new File(sourceFileUri[i]);


              try {
                     // open a URL connection to the Servlet
                  uploadingdata = true;
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(urlString);

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection();
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   boundary = "------------------boundary";
                   String tail = "\r\n--"+boundary+"--\r\n";
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setDoOutput(true);

                   String metadataPart = "--" + boundary + "\r\n"
                              + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
                              + "" + "\r\n";

                   String fileHeader1 = "--" + boundary + "\r\n"
                              + "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
                              + fileName + "\"\r\n"
                              + "Content-Type: application/octet-stream\r\n"
                              + "Content-Transfer-Encoding: binary\r\n";

                   long fileLength = sourceFile.length() + tail.length();
                          String fileHeader2 = "Content-length: " + fileLength + "\r\n";
                          String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
                          String stringData = metadataPart + fileHeader;

                   long requestLength = stringData.length() + fileLength;
                          conn.setRequestProperty("Content-length", "" + requestLength);
                          conn.setFixedLengthStreamingMode((int) requestLength);
                          conn.setRequestProperty("uploaded_file", fileName);
                          conn.setConnectTimeout(1000);
                          conn.setReadTimeout(1000);
                          conn.connect();

                   long endTime = new Date().getTime();
                   Log.d("StartTime","starttime: "+startTime);
                   Log.d("EndTime","endTime: "+endTime);
                   long timeoutStatus = (endTime-startTime)/1000;
                   Log.d("TimeOutStatus","timeoutStatus: "+timeoutStatus);

                   if(timeoutStatus>TIMEOUT_IN_SECONDS)
                   {
                       throw new Exception();
                   }
                   dos = new DataOutputStream(conn.getOutputStream());

                   dos.writeBytes(stringData);

                   int bytesRead, progress = 0;

                   byte[] buffer = new byte[1024];
                   BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));
                   String temp =null;
                   for(String retval :fileName.split("/")){
                       temp = retval;

                   }

                   while ((bytesRead = bufInput.read(buffer)) != -1) {
                       // write output
                       dos.write(buffer, 0, bytesRead);
                       dos.flush();
                       progress += bytesRead;
                       // update progress bar
                       nmBuilder.setProgress(100,(int) ((progress*100)/fileLength),false);
                       nmBuilder.setContentText("Uplaoding "+temp+" in progress");
                       notificationManager.notify(0,nmBuilder.build());

                     }

                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


                   serverResponseCode = conn.getResponseCode();
                   String serverResponseMessage = conn.getResponseMessage();

                   Log.i("uploadFile", "HTTP Response is : "
                           + serverResponseMessage + ": " + serverResponseCode);

                   if(serverResponseCode == 200){
                        nmBuilder.setProgress(0, 0,false);
                        nmBuilder.setContentText(temp+" Upload complete");
                        notificationManager.notify(0,nmBuilder.build());
                   }   

                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch(SocketException e){
                  System.out.println("SockeyException "+e);
              }
                  catch (MalformedURLException ex) {
                  ex.printStackTrace();

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
              }catch(SocketTimeoutException e)
              {
                  System.out.println("timeout exsception occured "+conn.getReadTimeout());
              }
              catch(Exception e) 
              {
                  e.printStackTrace();

                  Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
              }

            }
             return serverResponseCode;
  }
}
公共类MyService扩展服务{
公共静态最终字符串TAG=“MyService”;
连接检测器cd;
布尔值isInternetPresent=false;
boolean uploadingdata=false;
整数serverResponseCode=0;
字符串[]sourceFileUri;
字符串日期;
专用静态长超时(以秒为单位)=120;
@凌驾
公共IBinder onBind(意图arg0){
返回null;
}
专用TimerTask Chcknet=新TimerTask(){
@SuppressLint(“SimpleDataFormat”)
@凌驾
公开募捐{
//TODO自动生成的方法存根
SimpleDataFormat df=新的SimpleDataFormat(“HH:mm:ss”);
date=df.format(Calendar.getInstance().getTime());
cd=新连接检测器(getApplicationContext());
isInternetPresent=cd.isConnectingToInternet();
Log.d(标签“持续运行:”+日期);
Looper.prepare();
试一试{
如果(isInternetPresent)
{
如果(!上载数据)
{
Log.d(标签“call fetchdata”+日期);
fetchdata();
}否则{
Log.d(标签“已上传数据”+日期);
}
}
否则{
uploadingdata=false;
Log.d(标签“无互联网连接”);
}
}捕获(例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
loop.loop();
}   };
@SuppressLint(“SimpleDataFormat”)
public void onCreate()
{
字符串filePath=Environment.getExternalStorageDirectory()+“/logcat.txt”;
试一试{
Runtime.getRuntime().exec(新字符串[]{“logcat”、“-f”、文件路径、“MyAppTAG:V”、“*:S”});
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
定时器=新定时器();
定时表(Chcknet,1000L,20*1000L);
Log.d(标记“Fetchdata”+日期);
}
@SuppressLint(“SimpleDataFormat”)
公共int onStartCommand(Intent Intent、int标志、int Startid)
{
返回开始时间;
}
私有void fetchdata()
{
//TODO自动生成的方法存根
TestDatabase test_db=新的TestDatabase(此);
SQLiteDatabase db=test_db.getWritableDatabase();
Cursor Cursor=db.rawQuery(“从上传的测试数据中选择url,其中状态为“否”,null”);
cursor.getCount();
d(“标记”,“游标中的值:”+cursor.getCount());
sourceFileUri=新字符串[cursor.getCount()];
int i=0;
if(cursor.moveToFirst()){
做{
sourceFileUri[i]=cursor.getString(0);
i++;
}while(cursor.moveToNext());
d(标记,“uri字符串的长度:”+sourceFileUri.length);
}
if(sourceFileUri.length>0)
{
新建doFileUpload().execute(sourceFileUri);
}
}
类doFileUpload扩展了异步任务
{
通知经理通知经理;
通知建造商和建造商;
字符串文件名;
HttpURLConnection conn=null;
DataOutputStream dos=null;
long startTime=new Date().getTime();
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
弦边界;
文件源文件;
字符串URL字符串=”http://192.168.1.8:82/UploadToServer.php";
@SuppressLint(“新API”)
@凌驾
受保护的整数doInBackground(字符串…参数){
//TODO自动生成的方法存根
Log.d(标记“In-doFileUpload”+sourceFileUri);
nmBuilder=new Notification.Builder(getApplicationContext())
.setContentTitle(“上载文件”)
.setContentText(“正在上载”)
.setSmallIcon(R.drawable.ic_发射器);
Intent intt=newintent(getApplicationContext(),MyService.class);
PendingEvent pdint=PendingEvent.getActivity(getApplicationContext(),0,intt,PendingEvent.FLAG_UPDATE_CURRENT);
nmBuilder.setContentIntent(pdint);
notificationManager=(notificationManager)getSystemService(Context.NOTIFICATION\u服务);
notificationManager.notify(0,nmBuilder.build());

对于(int i=0;我请每次检查您的网络连接,然后继续!!没有得到您告诉我的,我正在使用oncreate方法中的计时器每20秒检查一次网络连接。哦,好的……如果我找到任何可行的答案,我将重新回答。当尝试运行此方法并启动服务时,还有一个问题ART上传图像文件并在上传的过程中,如果我断开网络,仿真器也从ADB断开连接,如果我刷新ADB重新连接仿真器,它会在LogAT I/Stout中显示下面的MSG。out(2871):SoKeKeExjavajava. NET.SokExtExp:Stto to失败:ItDimout(连接超时)I/So.out。(2871):SockeyException java.net.ConnectException:在1000毫秒后连接到/192.168.1.8(端口82)失败:连接失败:ENETUNREACH(网络无法访问)