Фоновая служба отображает исключение тайм-аута через некоторое время в Android 6

Это служба, работающая в фоновом режиме, без активности, начала работать нормально, но примерно через четыре часа будет ConnectTimeoutException,

Соединитесь с xxx.xxx.xxx.xxx тайм-аут.

Эта проблема возникает в Android 6, я не нашел эту проблему Android 4. При возникновении этой проблемы, я должен перезагрузить этот телефон, после чего он некоторое время правильно подключается. При возникновении этой проблемы другие сетевые приложения на телефоне работают правильно.

public class mService extends Service{

    Intent intent;
    private Handler objHandlerCheckNetwork = new Handler();
    private boolean mReflectFlg = false;
    private static final int NOTIFICATION_ID = 101;
    private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class };
    private static final Class<?>[] mStartForegroundSignature = new Class[] { int.class , Notification.class };
    private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
    private NotificationManager mNM;
    private Method mSetForeground;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mSetForegroundArgs = new Object[1];
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];

    private Runnable mHttpTestRunnable = new Runnable() {
        @Override
        public void run() {
            if (httpTest()){
                Log.e(GlobalData.getClassMethodName(),"true");
            }else{
                Log.e(GlobalData.getClassMethodName(),"false");
            }
        }
    };
    private Runnable mTasksCheckNetwork = new Runnable()
    {
        public void run()
        {
            Thread httpTestThread = new Thread(mHttpTestRunnable);;
            httpTestThread.start();
            objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000*30);
        }
    };


    @SuppressLint("NewApi")
    @Override
    public void onCreate() {
        super.onCreate();

        mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE );
        try {
            mStartForeground = mService.class.getMethod("startForeground" , mStartForegroundSignature);
            mStopForeground = mService.class.getMethod("stopForeground" , mStopForegroundSignature);
        } catch (NoSuchMethodException e) {
            mStartForeground = mStopForeground = null;
        }

        try {
            mSetForeground = getClass().getMethod( "setForeground", mSetForegroundSignature);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException( "OS doesn't have Service.startForeground OR Service.setForeground!");
        }
        Intent intent = new Intent(this,UploadTableDataService.class );
        intent.putExtra( "ficationId", NOTIFICATION_ID);
        Notification.Builder builder = new Notification.Builder(this);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(contentIntent);
        builder.setSmallIcon(R.drawable.gps);
        builder.setContentTitle( "test" );
        builder.setContentText( "test111" );
        Notification notification = builder.getNotification();


        startForegroundCompat( NOTIFICATION_ID, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        //startService( new Intent( this, WifiService. class));
        //startService( new Intent( this, VoiceService. class));
        this.intent = intent;
        Log.e(GlobalData.getClassMethodName(),"mService start!");
        objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000);
        return START_STICKY;
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        try{
            objHandlerCheckNetwork.removeCallbacks(mTasksCheckNetwork);
        }catch (Exception e) {
            Log.d("DEBUG->", "onDestroy error - removeUpdates: ");
        }

        //stopForegroundCompat( NOTIFICATION_ID);
    }

    void invokeMethod(Method method, Object[] args) {
        try {
            method.invoke( this, args);
        } catch (InvocationTargetException e) {
            // Should not happen.
            Log. w("ApiDemos" , "Unable to invoke method" , e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            Log. w("ApiDemos" , "Unable to invoke method" , e);
        }
    }

    /**
     * This is a wrapper around the new startForeground method, using the older
     * APIs if it is not available.
     */
    void startForegroundCompat( int id, Notification notification) {
        if ( mReflectFlg) {
            // If we have the new startForeground API, then use it.
            if ( mStartForeground != null) {
                mStartForegroundArgs[0] = Integer. valueOf(id);
                mStartForegroundArgs[1] = notification;
                invokeMethod( mStartForeground, mStartForegroundArgs);
                return;
            }

            // Fall back on the old API.
            mSetForegroundArgs[0] = Boolean. TRUE;
            invokeMethod( mSetForeground, mSetForegroundArgs);
            mNM.notify(id, notification);
        } else {


            if (Build.VERSION. SDK_INT >= 5) {
                startForeground(id, notification);
            } else {
                // Fall back on the old API.
                mSetForegroundArgs[0] = Boolean. TRUE;
                invokeMethod( mSetForeground, mSetForegroundArgs);
                mNM.notify(id, notification);
            }
        }
    }

    /**
     * This is a wrapper around the new stopForeground method, using the older
     * APIs if it is not available.
     */
    void stopForegroundCompat( int id) {
        if ( mReflectFlg) {
            // If we have the new stopForeground API, then use it.
            if ( mStopForeground != null) {
                mStopForegroundArgs[0] = Boolean. TRUE;
                invokeMethod( mStopForeground, mStopForegroundArgs);
                return;
            }

            mNM.cancel(id);
            mSetForegroundArgs[0] = Boolean. FALSE;
            invokeMethod( mSetForeground, mSetForegroundArgs);
        } else {


            if (Build.VERSION. SDK_INT >= 5) {
                stopForeground( true);
            } else {
                // Fall back on the old API. Note to cancel BEFORE changing the
                // foreground state, since we could be killed at that point.
                mNM.cancel(id);
                mSetForegroundArgs[0] = Boolean. FALSE;
                invokeMethod( mSetForeground, mSetForegroundArgs);
            }
        }
    }
    public static Boolean httpTest() {
        HttpClient client= new DefaultHttpClient();;
        try {
            StringBuilder sb = new StringBuilder();
            HttpParams httpParams = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 1000*5);
            HttpConnectionParams.setSoTimeout(httpParams, 1000*10);
            HttpResponse response = client.execute(new HttpGet("http://www.itnanny.com/default.htm"));

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);

                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                reader.close();
            }
            Log.e(GlobalData.getClassMethodName(),"result:"+sb.toString());
            if (sb.toString().indexOf("ok") > -1){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            client.getConnectionManager().shutdown();;
        }

        return false;
    }
}

0 ответов

Другие вопросы по тегам