在后台检查网络(android)

时间:2018-04-18 17:28:14

标签: android service

我有一项在后台工作的服务 如果互联网是真的 - 更新数据 错 - 没有任何事情发生

如何在服务范围内检查互联网?也许广播接收器,但我不明白我怎么能意识到这个

public class MyService extends Service {

final String LOG_TAG = "TEST";
public static final long NOTIFY_INTERVAL = 60 * 1000; // 60 секунд

// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
boolean isConnected; 

@Override
public void onCreate() {
    mTimer = new Timer();
    // schedule task
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0,
            NOTIFY_INTERVAL);
}

public int onStartCommand(Intent intent, int flags, int startId) {

    Log.d(LOG_TAG, "onStartCommand");
    return super.onStartCommand(intent, flags, startId);
}

public void onDestroy() {
    mTimer.cancel();
    Log.d(LOG_TAG, "onDestroy");
}

void someTask() {
    if (isConnected) {
        Toast.makeText(getApplicationContext(), "text",
                Toast.LENGTH_SHORT).show();
    }
}

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

class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                someTask();

            }
        });
    }
}

如果boolean是Connected true,请做一些事 那是我需要来自broadcastreceiver的服务接收结果

1 个答案:

答案 0 :(得分:-1)

试试这个

class CheckInternetConnection extends AsyncTask<Void, Void, Boolean>{
        @Override
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        protected Boolean doInBackground(Void... params) {
            if (isNetworkAvailable()) {
                try {
                    HttpURLConnection urlc = (HttpURLConnection)
                            (new URL("http://clients3.google.com/generate_204")
                                    .openConnection());
                    urlc.setRequestProperty("User-Agent", "Android");
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(1500);
                    urlc.connect();
                    return (urlc.getResponseCode() == 204 &&
                            urlc.getContentLength() == 0);
                } catch (IOException e) {
                    Log.e("WindActivity", "Error checking internet connection", e);
                }
            } else {
                Log.d("WindActivity", "No network available!");
            }
            return false;
        }

        private boolean isNetworkAvailable() {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if(result){
                //YOU HAVE INTERNET
                isConnected = true;
            }
            else
                //You Do not have internet
        }
    }

然后你可以像这样调用这个类

new CheckInternetConnection().execute();