Java Examples for android.net.TrafficStats

The following java examples will help you to understand the usage of android.net.TrafficStats. These source code samples are taken from different open source projects.

Example 1
Project: robolectric-master  File: ShadowTrafficStatsTest.java View source code
@Test
public void allQueriesAreStubbed() throws Exception {
    int anything = -2;
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getThreadStatsTag());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileTxPackets());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileRxPackets());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileTxBytes());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getMobileRxBytes());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalTxPackets());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalRxPackets());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalTxBytes());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getTotalRxBytes());
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTxBytes(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidRxBytes(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTxPackets(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidRxPackets(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpTxBytes(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpRxBytes(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpTxBytes(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpRxBytes(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpTxSegments(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidTcpRxSegments(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpTxPackets(anything));
    assertEquals(TrafficStats.UNSUPPORTED, TrafficStats.getUidUdpRxPackets(anything));
}
Example 2
Project: skandroid-core-master  File: TrafficStatsCollector.java View source code
public static TrafficData collectTraffic() {
    // https://developer.android.com/reference/android/net/TrafficStats.html#getMobileRxBytes%28%29
    // According to the Android documentation, any one of the methods on TrafficStats might fail to work!
    // In such cases where a method is not supported, the method returns UNSUPPORTED (-1)...
    TrafficData ret = new TrafficData();
    ret.time = System.currentTimeMillis();
    ret.mobileRxBytes = TrafficStats.getMobileRxBytes();
    if (ret.mobileRxBytes == TrafficStats.UNSUPPORTED) {
        ret.mobileRxBytes = 0;
    }
    ret.mobileTxBytes = TrafficStats.getMobileTxBytes();
    if (ret.mobileTxBytes == TrafficStats.UNSUPPORTED) {
        ret.mobileTxBytes = 0;
    }
    ret.totalRxBytes = TrafficStats.getTotalRxBytes();
    if (ret.totalRxBytes == TrafficStats.UNSUPPORTED) {
        ret.totalRxBytes = 0;
    }
    ret.totalTxBytes = TrafficStats.getTotalTxBytes();
    if (ret.totalTxBytes == TrafficStats.UNSUPPORTED) {
        ret.totalTxBytes = 0;
    }
    int uid = Process.myUid();
    ret.appRxBytes = TrafficStats.getUidRxBytes(uid);
    if (ret.appRxBytes == TrafficStats.UNSUPPORTED) {
        ret.appRxBytes = 0;
    }
    ret.appTxBytes = TrafficStats.getUidTxBytes(uid);
    if (ret.appTxBytes == TrafficStats.UNSUPPORTED) {
        ret.appTxBytes = 0;
    }
    return ret;
}
Example 3
Project: MobileGuard-master  File: TrafficStatsActivity.java View source code
/**
     * init data
     */
@Override
protected void initData() {
    long totalRxBytes = TrafficStats.getTotalRxBytes();
    long totalTxBytes = TrafficStats.getTotalTxBytes();
    long mobileRxBytes = TrafficStats.getMobileRxBytes();
    long mobileTxBytes = TrafficStats.getMobileTxBytes();
    long totalBytes = totalRxBytes + totalTxBytes;
    long mobileBytes = mobileRxBytes + mobileTxBytes;
    tvTotalTrafficStatsSum.setText(getString(R.string.total_traffic_stats_sum, Formatter.formatFileSize(this, totalBytes)));
    tvMobileTrafficStatsSum.setText(getString(R.string.mobile_traffic_stats_sum, Formatter.formatFileSize(this, mobileBytes)));
    tvTotalTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, totalTxBytes), Formatter.formatFileSize(this, totalRxBytes)));
    tvMobileTrafficStats.setText(getString(R.string.traffic_stats_upload_download, Formatter.formatFileSize(this, mobileTxBytes), Formatter.formatFileSize(this, mobileRxBytes)));
}
Example 4
Project: MobilePlayer1020-master  File: Utils.java View source code
/**
     * 显示网络速度
     * @param context
     * @return
     */
public String showNetSpeed(Context context) {
    //转为KB;
    long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);
    long nowTimeStamp = System.currentTimeMillis();
    //毫秒转�
    long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));
    lastTimeStamp = nowTimeStamp;
    lastTotalRxBytes = nowTotalRxBytes;
    String netSpeed = String.valueOf(speed) + " kb/s";
    return netSpeed;
}
Example 5
Project: androidperformance-master  File: AppUsageHelper.java View source code
public static Usage getUsageData(Context context) {
    Usage usage = new Usage();
    List<Application> result = new ArrayList<Application>();
    usage.setApplications(result);
    mPm = context.getPackageManager();
    ArrayList<String> runningNames = getRunningProcesses(context);
    List<ApplicationInfo> allInfo = mPm.getInstalledApplications(0);
    Set<Integer> uids = new TreeSet<Integer>();
    long total_recv = TrafficStats.getTotalRxBytes();
    long total_sent = TrafficStats.getTotalTxBytes();
    long mobile_recv = TrafficStats.getMobileRxBytes();
    long mobile_sent = TrafficStats.getMobileTxBytes();
    for (ApplicationInfo info : allInfo) {
        Integer uid = info.uid;
        if (uids.contains(uid))
            continue;
        uids.add((Integer) uid);
        long recv = TrafficStats.getUidRxBytes(uid);
        long sent = TrafficStats.getUidTxBytes(uid);
        // remove those application which do not sent and recv data
        if (recv > 0 || sent > 0) {
            Application app = new Application();
            app.setName(AppUsageUtil.getAppLabel(context, uid));
            app.setPackageName(AppUsageUtil.getAppPkg(context, uid));
            app.setIcon(AppUsageUtil.getAppIcon(context, uid));
            app.setTotal_recv(TrafficStats.getUidRxBytes(uid));
            app.setTotal_sent(TrafficStats.getUidTxBytes(uid));
            app.setIsRunning(runningNames.contains(AppUsageUtil.getAppPkg(context, uid)));
            result.add(app);
        }
    }
    usage.setTotal_recv(total_recv);
    usage.setTotal_sent(total_sent);
    usage.setMobile_recv(mobile_recv);
    usage.setMobile_sent(mobile_sent);
    return usage;
}
Example 6
Project: afwall-master  File: AppDetailActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle(getString(R.string.traffic_detail_title));
    setContentView(R.layout.app_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.app_toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    final Context ctx = getApplicationContext();
    ImageView image = (ImageView) findViewById(R.id.app_icon);
    TextView textView = (TextView) findViewById(R.id.app_title);
    TextView textView2 = (TextView) findViewById(R.id.app_package);
    TextView up = (TextView) findViewById(R.id.up);
    TextView down = (TextView) findViewById(R.id.down);
    /**/
    int appid = getIntent().getIntExtra("appid", -1);
    if (appid > 0) {
        final PackageManager packageManager = getApplicationContext().getPackageManager();
        final String[] packageNameList = ctx.getPackageManager().getPackagesForUid(appid);
        if (packageNameList != null) {
            packageName = packageNameList.length > 0 ? packageNameList[0] : ctx.getPackageManager().getNameForUid(appid);
        } else {
            packageName = ctx.getPackageManager().getNameForUid(appid);
        }
        Button button = (Button) findViewById(R.id.app_settings);
        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Api.showInstalledAppDetails(getApplicationContext(), packageName);
            }
        });
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            image.setImageDrawable(applicationInfo.loadIcon(packageManager));
            textView.setText(packageManager.getApplicationLabel(applicationInfo));
            if (packageNameList.length > 1) {
                textView2.setText(Arrays.toString(packageNameList));
                button.setEnabled(false);
            } else {
                textView2.setText(packageName);
            }
            long download_bytes = TrafficStats.getUidRxBytes(applicationInfo.uid);
            long uploaded_bytes = TrafficStats.getUidTxBytes(applicationInfo.uid);
            down.setText(" : " + humanReadableByteCount(download_bytes, false));
            up.setText(" : " + humanReadableByteCount(uploaded_bytes, false));
        } catch (final NameNotFoundException e) {
            long download_bytes = TrafficStats.getUidRxBytes(appid);
            long uploaded_bytes = TrafficStats.getUidTxBytes(appid);
            down.setText(" : " + humanReadableByteCount(download_bytes, false));
            up.setText(" : " + humanReadableByteCount(uploaded_bytes, false));
            button.setEnabled(false);
        }
    /*long total = TrafficStats.getTotalRxBytes();
        	long mobileTotal = TrafficStats.getMobileRxBytes();
        	long wifiTotal = (total - mobileTotal);
        	Log.v(TAG, "total=" + total + " mob=" + mobileTotal + " wifi=" + wifiTotal);*/
    }
}
Example 7
Project: Android-Next-master  File: TrafficUtils.java View source code
/**
     * 开始��统计
     *
     * @param context Context
     * @param tag     traffic tag
     * @return received bytes
     */
public static long start(Context context, String tag) {
    final int uid = getUid(context);
    if (uid > 0) {
        long appRxValue = TrafficStats.getUidRxBytes(uid);
        long appTxValue = TrafficStats.getUidTxBytes(uid);
        sReceivedBytes.put(tag, appRxValue);
        sSendBytes.put(tag, appTxValue);
        if (DEBUG) {
            LogUtils.v(TAG, "start() rxValue=" + appRxValue / 1000 + " txValue=" + appTxValue / 1000 + " uid=" + uid);
        }
        return appRxValue;
    }
    return 0;
}
Example 8
Project: android_packages_apps-master  File: EasSyncService.java View source code
/**
     * Common code to sync E+PIM data
     *
     * @param target an EasMailbox, EasContacts, or EasCalendar object
     */
public void sync(AbstractSyncAdapter target) throws IOException {
    Mailbox mailbox = target.mMailbox;
    boolean moreAvailable = true;
    int loopingCount = 0;
    while (!mStop && (moreAvailable || hasPendingRequests())) {
        // when connectivity has returned
        if (!hasConnectivity()) {
            userLog("No connectivity in sync; finishing sync");
            mExitStatus = EXIT_DONE;
            return;
        }
        // Every time through the loop we check to see if we're still syncable
        if (!target.isSyncable()) {
            mExitStatus = EXIT_DONE;
            return;
        }
        // Now, handle various requests
        while (true) {
            Request req = null;
            if (mRequestQueue.isEmpty()) {
                break;
            } else {
                req = mRequestQueue.peek();
            }
            // MeetingResponseRequest (respond to a meeting request)
            if (req instanceof PartRequest) {
                TrafficStats.setThreadStatsTag(TrafficFlags.getAttachmentFlags(mContext, mAccount));
                new AttachmentLoader(this, (PartRequest) req).loadAttachment();
                TrafficStats.setThreadStatsTag(TrafficFlags.getSyncFlags(mContext, mAccount));
            } else if (req instanceof MeetingResponseRequest) {
                sendMeetingResponse((MeetingResponseRequest) req);
            } else if (req instanceof MessageMoveRequest) {
                messageMoveRequest((MessageMoveRequest) req);
            }
            // If there's an exception handling the request, we'll throw it
            // Otherwise, we remove the request
            mRequestQueue.remove();
        }
        // Don't sync if we've got nothing to do
        if (!moreAvailable) {
            continue;
        }
        Serializer s = new Serializer();
        String className = target.getCollectionName();
        String syncKey = target.getSyncKey();
        userLog("sync, sending ", className, " syncKey: ", syncKey);
        s.start(Tags.SYNC_SYNC).start(Tags.SYNC_COLLECTIONS).start(Tags.SYNC_COLLECTION);
        // The "Class" element is removed in EAS 12.1 and later versions
        if (mProtocolVersionDouble < Eas.SUPPORTED_PROTOCOL_EX2007_SP1_DOUBLE) {
            s.data(Tags.SYNC_CLASS, className);
        }
        s.data(Tags.SYNC_SYNC_KEY, syncKey).data(Tags.SYNC_COLLECTION_ID, mailbox.mServerId);
        // Start with the default timeout
        int timeout = COMMAND_TIMEOUT;
        if (!syncKey.equals("0")) {
            // EAS doesn't allow GetChanges in an initial sync; sending other options
            // appears to cause the server to delay its response in some cases, and this delay
            // can be long enough to result in an IOException and total failure to sync.
            // Therefore, we don't send any options with the initial sync.
            // Set the truncation amount, body preference, lookback, etc.
            target.sendSyncOptions(mProtocolVersionDouble, s);
        } else {
            // Use enormous timeout for initial sync, which empirically can take a while longer
            timeout = 120 * SECONDS;
        }
        // Send our changes up to the server
        if (mUpsyncFailed) {
            if (Eas.USER_LOG) {
                Log.d(TAG, "Inhibiting upsync this cycle");
            }
        } else {
            target.sendLocalChanges(s);
        }
        s.end().end().end().done();
        EasResponse resp = sendHttpClientPost("Sync", new ByteArrayEntity(s.toByteArray()), timeout);
        try {
            int code = resp.getStatus();
            if (code == HttpStatus.SC_OK) {
                // In EAS 12.1, we can get "empty" sync responses, which indicate that there are
                // no changes in the mailbox; handle that case here
                // There are two cases here; if we get back a compressed stream (GZIP), we won't
                // know until we try to parse it (and generate an EmptyStreamException). If we
                // get uncompressed data, the response will be empty (i.e. have zero length)
                boolean emptyStream = false;
                if (!resp.isEmpty()) {
                    InputStream is = resp.getInputStream();
                    try {
                        moreAvailable = target.parse(is);
                        // If we inhibited upsync, we need yet another sync
                        if (mUpsyncFailed) {
                            moreAvailable = true;
                        }
                        if (target.isLooping()) {
                            loopingCount++;
                            userLog("** Looping: " + loopingCount);
                            // false and allow the sync loop to terminate
                            if (moreAvailable && (loopingCount > MAX_LOOPING_COUNT)) {
                                userLog("** Looping force stopped");
                                moreAvailable = false;
                            }
                        } else {
                            loopingCount = 0;
                        }
                        // do that if our upsync failed; clear the flag otherwise
                        if (!mUpsyncFailed) {
                            target.cleanup();
                        } else {
                            mUpsyncFailed = false;
                        }
                    } catch (EmptyStreamException e) {
                        userLog("Empty stream detected in GZIP response");
                        emptyStream = true;
                    } catch (CommandStatusException e) {
                        int status = e.mStatus;
                        if (CommandStatus.isNeedsProvisioning(status)) {
                            mExitStatus = EXIT_SECURITY_FAILURE;
                        } else if (CommandStatus.isDeniedAccess(status)) {
                            mExitStatus = EXIT_ACCESS_DENIED;
                        } else if (CommandStatus.isTransientError(status)) {
                            mExitStatus = EXIT_IO_ERROR;
                        } else {
                            mExitStatus = EXIT_EXCEPTION;
                        }
                        return;
                    }
                } else {
                    emptyStream = true;
                }
                if (emptyStream) {
                    // If this happens, exit cleanly, and change the interval from push to ping
                    // if necessary
                    userLog("Empty sync response; finishing");
                    if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) {
                        userLog("Changing mailbox from push to ping");
                        ContentValues cv = new ContentValues();
                        cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING);
                        mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId), cv, null, null);
                    }
                    if (mRequestQueue.isEmpty()) {
                        mExitStatus = EXIT_DONE;
                        return;
                    } else {
                        continue;
                    }
                }
            } else {
                userLog("Sync response error: ", code);
                if (EasResponse.isProvisionError(code)) {
                    mExitStatus = EXIT_SECURITY_FAILURE;
                } else if (EasResponse.isAuthError(code)) {
                    mExitStatus = EXIT_LOGIN_FAILURE;
                } else {
                    mExitStatus = EXIT_IO_ERROR;
                }
                return;
            }
        } finally {
            resp.close();
        }
    }
    mExitStatus = EXIT_DONE;
}
Example 9
Project: LEHomeMobile_android-master  File: HomeStateFragment.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    }
    mStartRX = TrafficStats.getUidRxBytes(mUid);
    mStartTX = TrafficStats.getUidTxBytes(mUid);
    if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setTitle("Uh Oh!");
        alert.setMessage("Your device does not support traffic stat monitoring.");
        alert.show();
        return;
    }
    mUid = android.os.Process.myUid();
}
Example 10
Project: NetSpeed-master  File: WindowUtil.java View source code
private void calculateNetSpeed() {
    rxBytes = TrafficStats.getTotalRxBytes();
    seBytes = TrafficStats.getTotalTxBytes() - rxBytes;
    double downloadSpeed = (rxBytes - preRxBytes) / 2;
    double uploadSpeed = (seBytes - preSeBytes) / 2;
    preRxBytes = rxBytes;
    preSeBytes = seBytes;
    //根�范围决定显示��
    String upSpeed = null;
    String downSpeed = null;
    NumberFormat df = java.text.NumberFormat.getNumberInstance();
    df.setMaximumFractionDigits(2);
    if (downloadSpeed > 1024 * 1024) {
        downloadSpeed /= (1024 * 1024);
        downSpeed = df.format(downloadSpeed) + "MB/s";
    } else if (downloadSpeed > 1024) {
        downloadSpeed /= (1024);
        downSpeed = df.format(downloadSpeed) + "KB/s";
    } else {
        downSpeed = df.format(downloadSpeed) + "B/s";
    }
    if (uploadSpeed > 1024 * 1024) {
        uploadSpeed /= (1024 * 1024);
        upSpeed = df.format(uploadSpeed) + "MB/s";
    } else if (uploadSpeed > 1024) {
        uploadSpeed /= (1024);
        upSpeed = df.format(uploadSpeed) + "KB/s";
    } else {
        upSpeed = df.format(uploadSpeed) + "B/s";
    }
    updateSpeed("↓ " + downSpeed, "↑ " + upSpeed);
}
Example 11
Project: network-connection-class-master  File: DeviceBandwidthSampler.java View source code
/**
   * Method for polling for the change in total bytes since last update and
   * adding it to the BandwidthManager.
   */
protected void addSample() {
    long newBytes = TrafficStats.getTotalRxBytes();
    long byteDiff = newBytes - sPreviousBytes;
    if (sPreviousBytes >= 0) {
        synchronized (this) {
            long curTimeReading = SystemClock.elapsedRealtime();
            mConnectionClassManager.addBandwidth(byteDiff, curTimeReading - mLastTimeReading);
            mLastTimeReading = curTimeReading;
        }
    }
    sPreviousBytes = newBytes;
}
Example 12
Project: network-monitor-master  File: SpeedTestUpload.java View source code
public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) {
    Log.v(TAG, "upload " + uploadConfig);
    // Make sure we have a file to upload
    if (!uploadConfig.file.exists())
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(TIMEOUT);
    ftp.setDataTimeout(TIMEOUT);
    ftp.setDefaultTimeout(TIMEOUT);
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }
    InputStream is = null;
    try {
        // Set buffer size of FTP client
        ftp.setBufferSize(1048576);
        // Open a connection to the FTP server
        ftp.connect(uploadConfig.server, uploadConfig.port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Login to the FTP server
        if (!ftp.login(uploadConfig.user, uploadConfig.password)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE);
        }
        // Try to change directories
        if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) {
            Log.v(TAG, "Upload: could not change path to " + uploadConfig.path);
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
        }
        // set the file type to be read as a binary file
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        // Upload the file
        is = new FileInputStream(uploadConfig.file);
        long before = System.currentTimeMillis();
        long txBytesBefore = TrafficStats.getTotalTxBytes();
        if (!ftp.storeFile(uploadConfig.file.getName(), is)) {
            ftp.disconnect();
            Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: " + ftp.getReplyCode() + ", error string: " + ftp.getReplyString());
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Calculate stats
        long after = System.currentTimeMillis();
        long txBytesAfter = TrafficStats.getTotalTxBytes();
        ftp.logout();
        ftp.disconnect();
        Log.v(TAG, "Upload complete");
        return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before, SpeedTestStatus.SUCCESS);
    } catch (SocketException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } catch (IOException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } finally {
        IoUtil.closeSilently(is);
    }
}
Example 13
Project: open-rmbt-master  File: WebsiteTestServiceImpl.java View source code
@Override
public void run() {
    WebsiteTestServiceImpl.this.processUid = Process.myUid();
    if (webView == null)
        webView = new WebView(context);
    webView.clearCache(true);
    final long start = System.nanoTime();
    System.out.println("Running WEBSITETASK " + targetUrl);
    boolean isTrafficServiceSupported = USE_PROCESS_UID_FOR_TRAFFIC_MEASUREMENT ? TrafficStats.getUidRxBytes(processUid) != TrafficStats.UNSUPPORTED : TrafficStats.getTotalRxBytes() != TrafficStats.UNSUPPORTED;
    if (!isTrafficServiceSupported) {
        trafficRxStart = -1;
        trafficTxStart = -1;
        trafficRxEnd = -1;
        trafficTxEnd = -1;
    } else {
        if (USE_PROCESS_UID_FOR_TRAFFIC_MEASUREMENT) {
            trafficTxStart = TrafficStats.getUidTxBytes(processUid);
            trafficRxStart = TrafficStats.getUidRxBytes(processUid);
        } else {
            trafficTxStart = TrafficStats.getTotalTxBytes();
            trafficRxStart = TrafficStats.getTotalRxBytes();
        }
    }
    Thread timeoutThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                System.out.println("WEBSITETASK STARTING TIMEOUT THREAD: " + timeOut + " ms");
                Thread.sleep(timeOut);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
                return;
            }
            if (!WebsiteTestServiceImpl.this.hasFinished() && listener != null) {
                setEndTrafficCounter();
                if (listener.onTimeoutReached(WebsiteTestServiceImpl.this)) {
                    System.out.println("WEBSITETESTTASK TIMEOUT");
                    WebsiteTestServiceImpl.this.handler.post(new Runnable() {

                        @Override
                        public void run() {
                            WebsiteTestServiceImpl.this.webView.stopLoading();
                        }
                    });
                }
            }
        }
    });
    timeoutThread.start();
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {

        /*
					@Override
					public boolean shouldOverrideUrlLoading(WebView view,
							String url) {
						view.loadUrl(url);
						return true;
					}
					*/
        @Override
        public void onLoadResource(WebView view, String url) {
            System.out.println("getting resource: " + url + " progress: " + view.getProgress());
            resourceCount.incrementAndGet();
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            WebsiteTestServiceImpl.this.isRunning.set(false);
            WebsiteTestServiceImpl.this.hasFinished.set(true);
            WebsiteTestServiceImpl.this.hasError.set(false);
            WebsiteTestServiceImpl.this.duration = System.nanoTime() - start;
            if (WebsiteTestServiceImpl.this.trafficRxStart != -1) {
                setEndTrafficCounter();
            }
            System.out.println("PAGE FINISHED " + targetUrl + " progress: " + view.getProgress() + "%, resources counter: " + resourceCount.get());
            if (listener != null) {
                listener.onRenderFinished(WebsiteTestServiceImpl.this);
            }
        }

        @Override
        public void onPageStarted(final WebView view, String url, Bitmap favicon) {
            WebsiteTestServiceImpl.this.isRunning.set(true);
            WebsiteTestServiceImpl.this.hasFinished.set(false);
            WebsiteTestServiceImpl.this.hasError.set(false);
            if (listener != null) {
                listener.onDownloadStarted(WebsiteTestServiceImpl.this);
            }
            System.out.println("PAGE STARTED " + targetUrl);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            WebsiteTestServiceImpl.this.isRunning.set(false);
            WebsiteTestServiceImpl.this.hasFinished.set(true);
            WebsiteTestServiceImpl.this.hasError.set(true);
            WebsiteTestServiceImpl.this.duration = System.nanoTime() - start;
            if (WebsiteTestServiceImpl.this.trafficRxStart != -1) {
                setEndTrafficCounter();
            }
            if (listener != null) {
                listener.onError(WebsiteTestServiceImpl.this);
            }
        }
    });
    AsyncHtmlStatusCodeRetriever task = new AsyncHtmlStatusCodeRetriever();
    task.setContentRetrieverListener(new ContentRetrieverListener() {

        @Override
        public void onContentFinished(Integer statusCode) {
            if (statusCode == null)
                statusCode = -1;
            WebsiteTestServiceImpl.this.statusCode = statusCode;
            if (statusCode >= 0) {
                //webView.loadDataWithBaseURL(targetUrl, htmlContent, "text/html", "utf-8", null);
                webView.loadUrl(targetUrl);
            //webView.loadData(htmlContent, "text/html", "utf-8");
            } else {
                WebsiteTestServiceImpl.this.isRunning.set(false);
                WebsiteTestServiceImpl.this.hasFinished.set(true);
                WebsiteTestServiceImpl.this.hasError.set(true);
                WebsiteTestServiceImpl.this.duration = System.nanoTime() - start;
                if (WebsiteTestServiceImpl.this.trafficRxStart != -1) {
                    setEndTrafficCounter();
                }
                if (listener != null) {
                    listener.onError(WebsiteTestServiceImpl.this);
                }
            }
        }
    });
    task.execute(targetUrl);
//webView.loadUrl(targetUrl);
}
Example 14
Project: platform_frameworks_support-master  File: TrafficStatsCompatIcs.java View source code
public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
    final ParcelFileDescriptor pfd = ParcelFileDescriptor.fromDatagramSocket(socket);
    TrafficStats.tagSocket(new DatagramSocketWrapper(socket, pfd.getFileDescriptor()));
    // The developer is still using the FD, so we need to detach it to
    // prevent the PFD finalizer from closing it in their face. We had to
    // wait until after the tagging call above, since detaching clears out
    // the getFileDescriptor() result which tagging depends on.
    pfd.detachFd();
}
Example 15
Project: acfun-new-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 16
Project: android-discourse-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 17
Project: android-sdk-sources-for-api-level-23-master  File: WifiStateMachine.java View source code
WifiLinkLayerStats getWifiLinkLayerStats(boolean dbg) {
    WifiLinkLayerStats stats = null;
    if (mWifiLinkLayerStatsSupported > 0) {
        String name = "wlan0";
        stats = mWifiNative.getWifiLinkLayerStats(name);
        if (name != null && stats == null && mWifiLinkLayerStatsSupported > 0) {
            mWifiLinkLayerStatsSupported -= 1;
        } else if (stats != null) {
            lastLinkLayerStatsUpdate = System.currentTimeMillis();
            mOnTime = stats.on_time;
            mTxTime = stats.tx_time;
            mRxTime = stats.rx_time;
            mRunningBeaconCount = stats.beacon_rx;
        }
    }
    if (stats == null || mWifiLinkLayerStatsSupported <= 0) {
        long mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
        long mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
        mWifiInfo.updatePacketRates(mTxPkts, mRxPkts);
    } else {
        mWifiInfo.updatePacketRates(stats);
    }
    if (useHalBasedAutoJoinOffload()) {
        sendMessage(CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION);
    }
    return stats;
}
Example 18
Project: Android-Volley-Example-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 19
Project: AndroidNetworkBench-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 20
Project: AndroidSource-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 21
Project: android_device_softwinner_cubieboard1-master  File: RadioInfo.java View source code
private final void updateDataStats2() {
    Resources r = getResources();
    long txPackets = TrafficStats.getMobileTxPackets();
    long rxPackets = TrafficStats.getMobileRxPackets();
    long txBytes = TrafficStats.getMobileTxBytes();
    long rxBytes = TrafficStats.getMobileRxBytes();
    String packets = r.getString(R.string.radioInfo_display_packets);
    String bytes = r.getString(R.string.radioInfo_display_bytes);
    sent.setText(txPackets + " " + packets + ", " + txBytes + " " + bytes);
    received.setText(rxPackets + " " + packets + ", " + rxBytes + " " + bytes);
}
Example 22
Project: android_frameworks_base-master  File: NetworkMonitor.java View source code
@Override
public void enter() {
    // cause us to exit and re-enter EvaluatingState.
    if (!mEvaluationTimer.isStarted()) {
        mEvaluationTimer.start();
    }
    sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
    if (mUidResponsibleForReeval != INVALID_UID) {
        TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
        mUidResponsibleForReeval = INVALID_UID;
    }
    mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
    mAttempts = 0;
}
Example 23
Project: android_tv_metro-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 24
Project: AppAssit-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 25
Project: AppJone-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 26
Project: ATK-master  File: ATKMonitorService.java View source code
/**
      * Only valid on API >= 8
      * @param uid process uid
      * @return transfered bytes for this uid
      */
private long getUidTxBytes(int uid) {
    String className = "android.net.TrafficStats";
    String methodName = "getUidTxBytes";
    try {
        Class<?> handler = Class.forName(className);
        Method m = handler.getDeclaredMethod(methodName, int.class);
        long result = (Long) m.invoke(handler.newInstance(), uid);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}
Example 27
Project: barterli_android-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= 14) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 28
Project: CustomVolley-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 29
Project: EasyLinkedInAndroid-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 30
Project: enhanced-volley-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= 14) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 31
Project: enhanced_volley-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= 14) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 32
Project: ExSample-master  File: RequestTickle.java View source code
/**
     * Starts the request and return {@link NetworkResponse} or null.
     */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public NetworkResponse start() {
    if (null == mRequest) {
        return null;
    }
    NetworkResponse networkResponse = null;
    long startTimeMs = SystemClock.elapsedRealtime();
    try {
        mRequest.addMarker("network-queue-take");
        // network request.
        if (mRequest.isCanceled()) {
            mRequest.finish("network-discard-cancelled");
            return null;
        }
        // Tag the request (if API >= 14)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            TrafficStats.setThreadStatsTag(mRequest.getTrafficStatsTag());
        }
        // Perform the network request.
        networkResponse = mNetwork.performRequest(mRequest);
        // we're done -- don't deliver a second identical response.
        if (networkResponse.notModified && mRequest.hasHadResponseDelivered()) {
            mRequest.finish("not-modified");
            return networkResponse;
        }
        // Parse the response here on the worker thread.
        response = mRequest.parseNetworkResponse(networkResponse);
        mRequest.addMarker("network-parse-complete");
        // TODO: Only update cache metadata instead of entire record for 304s.
        if (mCache != null && mRequest.shouldCache() && response.cacheEntry != null) {
            mCache.put(mRequest.getCacheKey(), response.cacheEntry);
            mRequest.addMarker("network-cache-written");
        }
        // Post the response back.
        mRequest.markDelivered();
        mDelivery.postResponse(mRequest, response);
    } catch (VolleyError volleyError) {
        networkResponse = volleyError.networkResponse;
        volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
        parseAndDeliverNetworkError(mRequest, volleyError);
    } catch (Exception e) {
        VolleyLog.e(e, "Unhandled exception %s", e.toString());
        VolleyError volleyError = new VolleyError(e);
        volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
        mDelivery.postError(mRequest, volleyError);
    }
    if (null == networkResponse) {
        networkResponse = new NetworkResponse(0, null, null, false);
    }
    return networkResponse;
}
Example 33
Project: frameworks_base_disabled-master  File: WifiService.java View source code
private void notifyOnDataActivity() {
    long sent, received;
    long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
    int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
    mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
    mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
    if (preTxPkts > 0 || preRxPkts > 0) {
        sent = mTxPkts - preTxPkts;
        received = mRxPkts - preRxPkts;
        if (sent > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
        }
        if (received > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_IN;
        }
        if (dataActivity != mDataActivity && !mScreenOff) {
            mDataActivity = dataActivity;
            for (AsyncChannel client : mClients) {
                client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
            }
        }
    }
}
Example 34
Project: gCore-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 35
Project: icareyou-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 36
Project: itrackmygps-android-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 37
Project: mobile-mba-androidapp-master  File: TrafficStatsCollector.java View source code
public static Data collectAll(long interval) {
    try {
        Thread.sleep(Constants.NET_ACTIVITY_CONDITION_WAIT_TIME);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    long startTime = System.currentTimeMillis();
    Logger.d(TrafficStatsCollector.class, "start collecting netData for " + interval / 1000 + "s");
    Data data = new Data();
    data.trx = TrafficStats.getTotalRxBytes();
    data.ttx = TrafficStats.getTotalTxBytes();
    try {
        Thread.sleep(interval);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Logger.d(TrafficStatsCollector.class, "finished collecting netData in: " + (System.currentTimeMillis() - startTime) / 1000 + "s");
    data.trx = TrafficStats.getTotalRxBytes() - data.trx;
    data.ttx = TrafficStats.getTotalTxBytes() - data.ttx;
    return data;
}
Example 38
Project: mobilevideo-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 39
Project: Mobilyzer-master  File: RRCTask.java View source code
/**
     * Determine how many packets, so far, have been sent (the contents of /proc/net/dev/). This is
     * a global value. We use this to determine if any other app anywhere on the phone may have sent
     * interfering traffic that might have changed the RRC state without our knowledge.
     * 
     * @return Two values: number of bytes or packets received at index 0, followed by the number
     *         sent at index 1.
     */
public long[] getPacketsSent() {
    long[] retval = { -1, -1 };
    if (bySize) {
        retval[0] = TrafficStats.getMobileRxBytes();
        retval[1] = TrafficStats.getMobileTxBytes();
    } else {
        retval[0] = TrafficStats.getMobileRxPackets();
        retval[1] = TrafficStats.getMobileTxPackets();
    }
    return retval;
}
Example 40
Project: MyCC98-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 41
Project: OMzen-master  File: TrafficMeter.java View source code
@Override
public void run() {
    long td = SystemClock.elapsedRealtime() - mLastUpdateTime;
    if (!mAttached) {
        return;
    }
    long currentRxBytes = mCanReadFromFile ? getTotalReceivedBytes() : TrafficStats.getTotalRxBytes();
    long newBytes = currentRxBytes - mTotalRxBytes;
    boolean disconnected = false;
    if (mCanReadFromFile && newBytes < 0) {
        // It's impossible to get a speed under 0
        currentRxBytes = 0;
        newBytes = 0;
        disconnected = true;
    }
    if (mTrafficMeterHide && newBytes == 0) {
        long trafficBurstBytes = (mCanReadFromFile && disconnected) ? mTotalRxBytes - mTrafficBurstStartBytes : currentRxBytes - mTrafficBurstStartBytes;
        if (trafficBurstBytes != 0 && mTrafficMeterSummaryTime != 0) {
            setText(formatTraffic(trafficBurstBytes, false));
            if (DEBUG)
                log("Traffic burst ended: " + trafficBurstBytes + "B in " + (SystemClock.elapsedRealtime() - mTrafficBurstStartTime) / 1000 + "s");
            mKeepOnUntil = SystemClock.elapsedRealtime() + mTrafficMeterSummaryTime;
            mTrafficBurstStartTime = Long.MIN_VALUE;
            mTrafficBurstStartBytes = currentRxBytes;
        }
    } else {
        if (mTrafficMeterHide && mTrafficBurstStartTime == Long.MIN_VALUE) {
            mTrafficBurstStartTime = mLastUpdateTime;
            mTrafficBurstStartBytes = mTotalRxBytes;
        }
        if (td > 0) {
            setText(formatTraffic(newBytes * 1000 / td, true));
        }
    }
    // Hide if there is no traffic
    if (mTrafficMeterHide && newBytes == 0) {
        if (getVisibility() != GONE && mKeepOnUntil < SystemClock.elapsedRealtime()) {
            setText("");
            setVisibility(View.GONE);
        }
    } else {
        if (getVisibility() != VISIBLE) {
            setVisibility(View.VISIBLE);
        }
    }
    mTotalRxBytes = (mCanReadFromFile && disconnected) ? mTotalRxBytes : currentRxBytes;
    mLastUpdateTime = SystemClock.elapsedRealtime();
    getHandler().postDelayed(mRunnable, mInterval);
}
Example 42
Project: petsworld-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 43
Project: platform_frameworks_base-master  File: MountService.java View source code
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
    mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
    final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ", 160);
    synchronized (mLock) {
        pw.println("Disks:");
        pw.increaseIndent();
        for (int i = 0; i < mDisks.size(); i++) {
            final DiskInfo disk = mDisks.valueAt(i);
            disk.dump(pw);
        }
        pw.decreaseIndent();
        pw.println();
        pw.println("Volumes:");
        pw.increaseIndent();
        for (int i = 0; i < mVolumes.size(); i++) {
            final VolumeInfo vol = mVolumes.valueAt(i);
            if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id))
                continue;
            vol.dump(pw);
        }
        pw.decreaseIndent();
        pw.println();
        pw.println("Records:");
        pw.increaseIndent();
        for (int i = 0; i < mRecords.size(); i++) {
            final VolumeRecord note = mRecords.valueAt(i);
            note.dump(pw);
        }
        pw.decreaseIndent();
        pw.println();
        pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
        final Pair<String, Long> pair = StorageManager.getPrimaryStoragePathAndSize();
        if (pair == null) {
            pw.println("Internal storage total size: N/A");
        } else {
            pw.print("Internal storage (");
            pw.print(pair.first);
            pw.print(") total size: ");
            pw.print(pair.second);
            pw.print(" (");
            pw.print((float) pair.second / TrafficStats.GB_IN_BYTES);
            pw.println(" GB)");
        }
        pw.println("Force adoptable: " + mForceAdoptable);
        pw.println();
        pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
        pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
    }
    synchronized (mObbMounts) {
        pw.println();
        pw.println("mObbMounts:");
        pw.increaseIndent();
        final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
        while (binders.hasNext()) {
            Entry<IBinder, List<ObbState>> e = binders.next();
            pw.println(e.getKey() + ":");
            pw.increaseIndent();
            final List<ObbState> obbStates = e.getValue();
            for (final ObbState obbState : obbStates) {
                pw.println(obbState);
            }
            pw.decreaseIndent();
        }
        pw.decreaseIndent();
        pw.println();
        pw.println("mObbPathToStateMap:");
        pw.increaseIndent();
        final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
        while (maps.hasNext()) {
            final Entry<String, ObbState> e = maps.next();
            pw.print(e.getKey());
            pw.print(" -> ");
            pw.println(e.getValue());
        }
        pw.decreaseIndent();
    }
    pw.println();
    pw.println("mConnector:");
    pw.increaseIndent();
    mConnector.dump(fd, pw, args);
    pw.decreaseIndent();
    pw.println();
    pw.println("mCryptConnector:");
    pw.increaseIndent();
    mCryptConnector.dump(fd, pw, args);
    pw.decreaseIndent();
    pw.println();
    pw.print("Last maintenance: ");
    pw.println(TimeUtils.formatForLogging(mLastMaintenance));
}
Example 44
Project: prayerbox-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 45
Project: Project-M-1-master  File: RadioInfo.java View source code
private final void updateDataStats2() {
    Resources r = getResources();
    long txPackets = TrafficStats.getMobileTxPackets();
    long rxPackets = TrafficStats.getMobileRxPackets();
    long txBytes = TrafficStats.getMobileTxBytes();
    long rxBytes = TrafficStats.getMobileRxBytes();
    String packets = r.getString(R.string.radioInfo_display_packets);
    String bytes = r.getString(R.string.radioInfo_display_bytes);
    sent.setText(txPackets + " " + packets + ", " + txBytes + " " + bytes);
    received.setText(rxPackets + " " + packets + ", " + rxBytes + " " + bytes);
}
Example 46
Project: property-db-master  File: WifiService.java View source code
private void notifyOnDataActivity() {
    long sent, received;
    long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
    int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
    mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
    mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
    if (preTxPkts > 0 || preRxPkts > 0) {
        sent = mTxPkts - preTxPkts;
        received = mRxPkts - preRxPkts;
        if (sent > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
        }
        if (received > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_IN;
        }
        if (dataActivity != mDataActivity && !mScreenOff) {
            mDataActivity = dataActivity;
            for (AsyncChannel client : mClients) {
                client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
            }
        }
    }
}
Example 47
Project: Rocket-master  File: NetworkDispatcher.java View source code
@SuppressLint("NewApi")
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (RocketError rocketError) {
            parseAndDeliverNetworkError(request, rocketError);
        } catch (Exception e) {
            Log.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new RocketError(e));
        }
    }
}
Example 48
Project: sandro-master  File: TrafficStatsActivity.java View source code
private void getAppInfo() {
    PackageManager pm = MainApp.getContext().getPackageManager();
    List<PackageInfo> listPackages = pm.getInstalledPackages(0);
    List<String> processData = new ArrayList<String>();
    for (PackageInfo pi : listPackages) {
        int uid = pi.applicationInfo.uid;
        long total = (TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid)) / 1024;
        if (total > 0) {
            String appName = (String) pi.applicationInfo.loadLabel(pm);
            if (appName != null) {
                processData.add(appName + " : " + total + "KB");
            }
        }
    }
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(TrafficStatsActivity.this, android.R.layout.simple_list_item_1, processData);
    setListAdapter(dataAdapter);
}
Example 49
Project: SGU-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 50
Project: show-client-master  File: VideoPlayerJPActivity.java View source code
private void initVedioDate() {
    mStatue = STATUE_PRE_LOADING;
    isRequset = 0;
    mSeekBar.setEnabled(false);
    mSeekBar.setProgress(0);
    mTotalTimeTextView.setText("--:--");
    mPreLoadLayout.setVisibility(View.VISIBLE);
    mNoticeLayout.setVisibility(View.VISIBLE);
    mContinueLayout.setVisibility(View.GONE);
    mControlLayout.setVisibility(View.GONE);
    mDateLoadingLayout.setVisibility(View.GONE);
    // 获�网络速度
    mStartRX = TrafficStats.getTotalRxBytes();
    if (mStartRX == TrafficStats.UNSUPPORTED) {
        mSpeedTextView.setText("Your device does not support traffic stat monitoring.");
    } else {
        mHandler.postDelayed(mLoadingRunnable, 500);
    }
    // 点击�部影片播放时,会全局设置CurrentPlayData
    CurrentPlayDetailData playDate = app.getmCurrentPlayDetailData();
    if (// 如果�设置就�播放
    playDate == null) {
        Log.e(TAG, "playDate----->null");
        finish();
        return;
    }
    // �始化基本播放数�
    mProd_id = playDate.prod_id;
    mProd_type = playDate.prod_type;
    mProd_name = playDate.prod_name;
    mProd_sub_name = playDate.prod_sub_name;
    currentPlayUrl = playDate.prod_url;
    url_temp = playDate.prod_url;
    mDefination = playDate.prod_qua;
    lastTime = (int) playDate.prod_time;
    mProd_src = playDate.prod_src;
    isOnline = playDate.isOnline;
    if (mProd_type == TYPE_PUSH || mProd_type == TYPE_LOCAL || mProd_type == TYPE_PUSH_BT_EPISODE) {
        play_info = (MoviePlayHistoryInfo) playDate.obj;
    }
    Log.d(TAG, "name ----->" + mProd_name);
    Log.d(TAG, "currentPlayUrl ----->" + currentPlayUrl);
    Log.d(TAG, "mProd_type ----->" + mProd_type);
    if (mDefination == 0) {
        mDefination = 8;
    }
    // 更新播放��和上次播放时间
    updateSourceAndTime();
    updateName();
    switch(mProd_type) {
        case //迅雷 传递-10
        TYPE_XUNLEI:
            //å?–list
            MyApp.pool.execute(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    XLLXFileInfo xllxFileInfo = (XLLXFileInfo) app.getmCurrentPlayDetailData().obj;
                    if (xllxFileInfo != null && !xllxFileInfo.isDir) {
                        ArrayList<VideoPlayUrl> list = XunLeiLiXianUtil.getLXPlayUrl(VideoPlayerJPActivity.this, xllxFileInfo);
                        mJoyplusSubManager.setSubUri(XunLeiLiXianUtil.getSubtitleList(VideoPlayerJPActivity.this, xllxFileInfo));
                        mSubTitleView.displaySubtitle();
                        if (list != null && list.size() > 0) {
                            if (playUrls != null && playUrls.size() > 0) {
                                playUrls.clear();
                            }
                            for (int i = 0; i < list.size(); i++) {
                                VideoPlayUrl videoPlayUrl = list.get(i);
                                Log.i(TAG, "VideoPlayUrl--->" + videoPlayUrl.toString());
                                if (videoPlayUrl != null && videoPlayUrl.playurl != null) {
                                    URLS_INDEX url = new URLS_INDEX();
                                    url.url = videoPlayUrl.playurl;
                                    url.source_from = "XUNLEI";
                                    // can drag hd2 hd mp4 
                                    if (videoPlayUrl.isCanDrag) {
                                        if (videoPlayUrl.sharp != null) {
                                            int index = videoPlayUrl.sharp.getIndex();
                                            switch(index) {
                                                case 0:
                                                    url.defination_from_server = "mp4";
                                                    break;
                                                case 2:
                                                    url.defination_from_server = "hd";
                                                    break;
                                                case 3:
                                                    url.defination_from_server = "hd2";
                                                    break;
                                                default:
                                                    break;
                                            }
                                        }
                                    //can't drag flv
                                    } else {
                                        url.defination_from_server = "flv";
                                    //										playUrls_flv.a
                                    }
                                    playUrls.add(url);
                                }
                            }
                        }
                    }
                    initFourList();
                    sortPushUrls(mDefination);
                    mHandler.sendEmptyMessage(MESSAGE_URLS_READY);
                }
            });
            break;
        case //本地
        TYPE_LOCAL:
            if (currentPlayUrl != null) {
                mHandler.sendEmptyMessage(MESSAGE_PALY_URL_OK);
            } else {
                finish();
            }
            break;
        case //推�
        TYPE_PUSH:
            MyApp.pool.execute(new getPlayList());
            break;
        case // BT�集
        TYPE_PUSH_BT_EPISODE:
            MyApp.pool.execute(new getEpisodePlayUrls());
            break;
        default:
            if (currentPlayUrl != null && URLUtil.isNetworkUrl(currentPlayUrl)) {
                mHandler.sendEmptyMessage(MESSAGE_PALY_URL_OK);
            } else {
                if (// 如果�为空,获��务器返回的详细数�
                app.get_ReturnProgramView() != null) {
                    m_ReturnProgramView = app.get_ReturnProgramView();
                    mHandler.sendEmptyMessage(MESSAGE_RETURN_DATE_OK);
                } else // 如果为空,就�新获�
                {
                    getProgramViewDetailServiceData();
                }
            }
            break;
    }
}
Example 51
Project: sitecore-android-sdk-master  File: NetworkDispatcher.java View source code
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 52
Project: skip-android-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 53
Project: SmartCommunity-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 54
Project: super_volley-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 55
Project: TBase-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    //设置线程优先级
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request. 执行网络请求。
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.在这里工作线程解��应。
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 56
Project: technology-android-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 57
Project: TNetwork-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    //设置线程优先级
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request. 执行网络请求。
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.在这里工作线程解��应。
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 58
Project: trending-round-android-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 59
Project: volley-fix-http-response-header-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 60
Project: VolleyAir-master  File: RequestTickle.java View source code
/**
     * Starts the request and return {@link NetworkResponse} or null.
     */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public NetworkResponse start() {
    if (null == mRequest) {
        return null;
    }
    NetworkResponse networkResponse = null;
    long startTimeMs = SystemClock.elapsedRealtime();
    try {
        mRequest.addMarker("network-queue-take");
        // network request.
        if (mRequest.isCanceled()) {
            mRequest.finish("network-discard-cancelled");
            return null;
        }
        // Tag the request (if API >= 14)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            TrafficStats.setThreadStatsTag(mRequest.getTrafficStatsTag());
        }
        // Perform the network request.
        networkResponse = mNetwork.performRequest(mRequest);
        // we're done -- don't deliver a second identical response.
        if (networkResponse.notModified && mRequest.hasHadResponseDelivered()) {
            mRequest.finish("not-modified");
            return networkResponse;
        }
        // Parse the response here on the worker thread.
        response = mRequest.parseNetworkResponse(networkResponse);
        mRequest.addMarker("network-parse-complete");
        // TODO: Only update cache metadata instead of entire record for 304s.
        if (mCache != null && mRequest.shouldCache() && response.cacheEntry != null) {
            mCache.put(mRequest.getCacheKey(), response.cacheEntry);
            mRequest.addMarker("network-cache-written");
        }
        // Post the response back.
        mRequest.markDelivered();
        mDelivery.postResponse(mRequest, response);
    } catch (VolleyError volleyError) {
        networkResponse = volleyError.networkResponse;
        volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
        parseAndDeliverNetworkError(mRequest, volleyError);
    } catch (Exception e) {
        VolleyLog.e(e, "Unhandled exception %s", e.toString());
        VolleyError volleyError = new VolleyError(e);
        volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
        mDelivery.postError(mRequest, volleyError);
    }
    if (null == networkResponse) {
        networkResponse = new NetworkResponse(0, null, null, false);
    }
    return networkResponse;
}
Example 61
Project: VolleyPlus-master  File: RequestTickle.java View source code
/**
     * Starts the request and return {@link NetworkResponse} or null.
     */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public NetworkResponse start() {
    if (null == mRequest) {
        return null;
    }
    NetworkResponse networkResponse = null;
    long startTimeMs = SystemClock.elapsedRealtime();
    try {
        mRequest.addMarker("network-queue-take");
        // network request.
        if (mRequest.isCanceled()) {
            mRequest.finish("network-discard-cancelled");
            return null;
        }
        // Tag the request (if API >= 14)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            TrafficStats.setThreadStatsTag(mRequest.getTrafficStatsTag());
        }
        // Perform the network request.
        networkResponse = mNetwork.performRequest(mRequest);
        // we're done -- don't deliver a second identical response.
        if (networkResponse.notModified && mRequest.hasHadResponseDelivered()) {
            mRequest.finish("not-modified");
            return networkResponse;
        }
        // Parse the response here on the worker thread.
        response = mRequest.parseNetworkResponse(networkResponse);
        mRequest.addMarker("network-parse-complete");
        // TODO: Only update cache metadata instead of entire record for 304s.
        if (mCache != null && mRequest.shouldCache() && response.cacheEntry != null) {
            mCache.put(mRequest.getCacheKey(), response.cacheEntry);
            mRequest.addMarker("network-cache-written");
        }
        // Post the response back.
        mRequest.markDelivered();
        mDelivery.postResponse(mRequest, response);
    } catch (VolleyError volleyError) {
        networkResponse = volleyError.networkResponse;
        volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
        parseAndDeliverNetworkError(mRequest, volleyError);
    } catch (Exception e) {
        VolleyLog.e(e, "Unhandled exception %s", e.toString());
        VolleyError volleyError = new VolleyError(e);
        volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
        mDelivery.postError(mRequest, volleyError);
    }
    if (null == networkResponse) {
        networkResponse = new NetworkResponse(0, null, null, false);
    }
    return networkResponse;
}
Example 62
Project: VollyFullExample-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // Tag the request (if API >= 14)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 63
Project: platform_packages_apps_settings-master  File: RadioInfo.java View source code
private final void updateDataStats2() {
    Resources r = getResources();
    long txPackets = TrafficStats.getMobileTxPackets();
    long rxPackets = TrafficStats.getMobileRxPackets();
    long txBytes = TrafficStats.getMobileTxBytes();
    long rxBytes = TrafficStats.getMobileRxBytes();
    String packets = r.getString(R.string.radioInfo_display_packets);
    String bytes = r.getString(R.string.radioInfo_display_bytes);
    sent.setText(txPackets + " " + packets + ", " + txBytes + " " + bytes);
    received.setText(rxPackets + " " + packets + ", " + rxBytes + " " + bytes);
}
Example 64
Project: Android-Remote-master  File: ConnectionFragment.java View source code
@SuppressLint("SetTextI18n")
private void updateData() {
    if (App.ClementineConnection == null) {
        return;
    }
    long diff = new Date().getTime() - App.ClementineConnection.getStartTime();
    String dateFormat = String.format(Locale.US, "%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(diff), TimeUnit.MILLISECONDS.toMinutes(diff) % 60, TimeUnit.MILLISECONDS.toSeconds(diff) % 60);
    tv_time.setText(dateFormat);
    int uid = getActivity().getApplicationInfo().uid;
    if (TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED) {
        tv_traffic.setText(R.string.connection_traffic_unsupported);
    } else {
        String tx = Utilities.humanReadableBytes(TrafficStats.getUidTxBytes(uid) - App.ClementineConnection.getStartTx(), true);
        String rx = Utilities.humanReadableBytes(TrafficStats.getUidRxBytes(uid) - App.ClementineConnection.getStartRx(), true);
        long total = TrafficStats.getUidTxBytes(uid) - App.ClementineConnection.getStartTx() + TrafficStats.getUidRxBytes(uid) - App.ClementineConnection.getStartRx();
        if (TimeUnit.MILLISECONDS.toSeconds(diff) != 0) {
            long a = total / TimeUnit.MILLISECONDS.toSeconds(diff);
            String perSecond = Utilities.humanReadableBytes(a, true);
            tv_traffic.setText(tx + " / " + rx + " (" + perSecond + "/s)");
        }
    }
}
Example 65
Project: clementine-android-master  File: ConnectionFragment.java View source code
@SuppressLint("SetTextI18n")
private void updateData() {
    if (App.ClementineConnection == null) {
        return;
    }
    long diff = new Date().getTime() - App.ClementineConnection.getStartTime();
    String dateFormat = String.format(Locale.US, "%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(diff), TimeUnit.MILLISECONDS.toMinutes(diff) % 60, TimeUnit.MILLISECONDS.toSeconds(diff) % 60);
    tv_time.setText(dateFormat);
    int uid = getActivity().getApplicationInfo().uid;
    if (TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED) {
        tv_traffic.setText(R.string.connection_traffic_unsupported);
    } else {
        String tx = Utilities.humanReadableBytes(TrafficStats.getUidTxBytes(uid) - App.ClementineConnection.getStartTx(), true);
        String rx = Utilities.humanReadableBytes(TrafficStats.getUidRxBytes(uid) - App.ClementineConnection.getStartRx(), true);
        long total = TrafficStats.getUidTxBytes(uid) - App.ClementineConnection.getStartTx() + TrafficStats.getUidRxBytes(uid) - App.ClementineConnection.getStartRx();
        if (TimeUnit.MILLISECONDS.toSeconds(diff) != 0) {
            long a = total / TimeUnit.MILLISECONDS.toSeconds(diff);
            String perSecond = Utilities.humanReadableBytes(a, true);
            tv_traffic.setText(tx + " / " + rx + " (" + perSecond + "/s)");
        }
    }
}
Example 66
Project: Fast-Android-Networking-master  File: RxInternalNetworking.java View source code
@Override
public void request(long n) {
    if (n < 0)
        throw new IllegalArgumentException("n < 0: " + n);
    // Nothing to do when requesting 0.
    if (n == 0)
        return;
    // Request was already triggered.
    if (!compareAndSet(false, true))
        return;
    Response okHttpResponse = null;
    try {
        final long startTime = System.currentTimeMillis();
        final long startBytes = TrafficStats.getTotalRxBytes();
        okHttpResponse = call.execute();
        final long timeTaken = System.currentTimeMillis() - startTime;
        if (okHttpResponse.cacheResponse() == null) {
            final long finalBytes = TrafficStats.getTotalRxBytes();
            final long diffBytes;
            if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
                diffBytes = okHttpResponse.body().contentLength();
            } else {
                diffBytes = finalBytes - startBytes;
            }
            ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (request.getRequestBody() != null && request.getRequestBody().contentLength() != 0) ? request.getRequestBody().contentLength() : -1, okHttpResponse.body().contentLength(), false);
        } else if (request.getAnalyticsListener() != null) {
            if (okHttpResponse.networkResponse() == null) {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true);
            } else {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (request.getRequestBody() != null && request.getRequestBody().contentLength() != 0) ? request.getRequestBody().contentLength() : -1, 0, true);
            }
        }
        if (okHttpResponse.code() >= 400) {
            if (!subscriber.isUnsubscribed()) {
                subscriber.onError(Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code()));
            }
        } else {
            ANResponse<T> response = request.parseResponse(okHttpResponse);
            if (!response.isSuccess()) {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onError(response.getError());
                }
            } else {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onNext(response.getResult());
                }
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onCompleted();
                }
            }
        }
    } catch (IOException ioe) {
        if (!subscriber.isUnsubscribed()) {
            subscriber.onError(Utils.getErrorForConnection(new ANError(ioe)));
        }
    } catch (Exception e) {
        Exceptions.throwIfFatal(e);
        if (!subscriber.isUnsubscribed()) {
            subscriber.onError(Utils.getErrorForNetworkOnMainThreadOrConnection(e));
        }
    } finally {
        SourceCloseUtil.close(okHttpResponse, request);
    }
}
Example 67
Project: GeoAlarm-master  File: RouteMap.java View source code
/**
	 * Updates the stored usage data with the most up-to-date numbers
	 */
public void updateUsageData() {
    if (database != null) {
        long numBytesLastReceivedSession = database.getBytes(GeoAlarmDB.DB_RX_SESSION);
        long numBytesLastTransmittedSession = database.getBytes(GeoAlarmDB.DB_TX_SESSION);
        long numBytesReceived = database.getBytes(GeoAlarmDB.DB_RX);
        long numBytesTransmitted = database.getBytes(GeoAlarmDB.DB_TX);
        long numBytesReceivedDelta = TrafficStats.getUidRxBytes(Process.myUid()) - database.getBytes(GeoAlarmDB.DB_RX_TARE_SESSION) - numBytesLastReceivedSession;
        long numBytesTransmittedDelta = TrafficStats.getUidTxBytes(Process.myUid()) - database.getBytes(GeoAlarmDB.DB_TX_TARE_SESSION) - numBytesLastTransmittedSession;
        database.setBytes(GeoAlarmDB.DB_RX_SESSION, numBytesLastReceivedSession + numBytesReceivedDelta);
        database.setBytes(GeoAlarmDB.DB_TX_SESSION, numBytesLastTransmittedSession + numBytesTransmittedDelta);
        database.setBytes(GeoAlarmDB.DB_RX, numBytesReceived + numBytesReceivedDelta);
        database.setBytes(GeoAlarmDB.DB_TX, numBytesTransmitted + numBytesTransmittedDelta);
    }
}
Example 68
Project: nitrogen-master  File: NetworkTraffic.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.network_traffic);
    loadResources();
    ContentResolver resolver = getActivity().getContentResolver();
    mNetTrafficState = (ListPreference) findPreference(NETWORK_TRAFFIC_STATE);
    mNetTrafficUnit = (ListPreference) findPreference(NETWORK_TRAFFIC_UNIT);
    mNetTrafficPeriod = (ListPreference) findPreference(NETWORK_TRAFFIC_PERIOD);
    mNetTrafficAutohide = (SwitchPreference) findPreference(NETWORK_TRAFFIC_AUTOHIDE);
    mNetTrafficAutohide.setChecked((Settings.System.getInt(getContentResolver(), Settings.System.NETWORK_TRAFFIC_AUTOHIDE, 0) == 1));
    mNetTrafficAutohide.setOnPreferenceChangeListener(this);
    mNetTrafficAutohideThreshold = (CustomSeekBarPreference) findPreference(NETWORK_TRAFFIC_AUTOHIDE_THRESHOLD);
    int netTrafficAutohideThreshold = Settings.System.getInt(resolver, Settings.System.NETWORK_TRAFFIC_AUTOHIDE_THRESHOLD, 10);
    mNetTrafficAutohideThreshold.setValue(netTrafficAutohideThreshold / 1);
    mNetTrafficAutohideThreshold.setOnPreferenceChangeListener(this);
    // TrafficStats will return UNSUPPORTED if the device does not support it.
    if (TrafficStats.getTotalTxBytes() != TrafficStats.UNSUPPORTED && TrafficStats.getTotalRxBytes() != TrafficStats.UNSUPPORTED) {
        mNetTrafficVal = Settings.System.getInt(getContentResolver(), Settings.System.NETWORK_TRAFFIC_STATE, 0);
        int intIndex = mNetTrafficVal & (MASK_UP + MASK_DOWN);
        intIndex = mNetTrafficState.findIndexOfValue(String.valueOf(intIndex));
        updateNetworkTrafficState(intIndex);
        mNetTrafficState.setValueIndex(intIndex >= 0 ? intIndex : 0);
        mNetTrafficState.setSummary(mNetTrafficState.getEntry());
        mNetTrafficState.setOnPreferenceChangeListener(this);
        mNetTrafficUnit.setValueIndex(getBit(mNetTrafficVal, MASK_UNIT) ? 1 : 0);
        mNetTrafficUnit.setSummary(mNetTrafficUnit.getEntry());
        mNetTrafficUnit.setOnPreferenceChangeListener(this);
        intIndex = (mNetTrafficVal & MASK_PERIOD) >>> 16;
        intIndex = mNetTrafficPeriod.findIndexOfValue(String.valueOf(intIndex));
        mNetTrafficPeriod.setValueIndex(intIndex >= 0 ? intIndex : 1);
        mNetTrafficPeriod.setSummary(mNetTrafficPeriod.getEntry());
        mNetTrafficPeriod.setOnPreferenceChangeListener(this);
    }
}
Example 69
Project: openxface-android-master  File: XTrafficStats.java View source code
/**
     * �始化��数�
     */
private void initTrafficStats() {
    mWifiTraffic = new XWifiTraffic(mUID);
    mMobileTraffic = new XMobileTraffic(mUID);
    mNoNetworkTraffic = new XNoNetworkTraffic(mUID);
    updateCurrentNetwork(mContext);
    long totalTraffic = TrafficStats.getUidRxBytes(mUID);
    mCurrentNetworkState.updateTotalTraffic(totalTraffic);
}
Example 70
Project: packages_apps_ROMControl-master  File: TrafficSettingsFragment.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.fragment_traffic_settings);
    loadResources();
    PreferenceScreen prefSet = getPreferenceScreen();
    mNetTrafficState = (ListPreference) prefSet.findPreference(NETWORK_TRAFFIC_STATE);
    mNetTrafficUnit = (ListPreference) prefSet.findPreference(NETWORK_TRAFFIC_UNIT);
    mNetTrafficPeriod = (ListPreference) prefSet.findPreference(NETWORK_TRAFFIC_PERIOD);
    mNetTrafficAutohide = (SwitchPreference) prefSet.findPreference(NETWORK_TRAFFIC_AUTOHIDE);
    mNetTrafficAutohide.setChecked((Settings.System.getInt(getActivity().getContentResolver(), Settings.System.NETWORK_TRAFFIC_AUTOHIDE, 0) == 1));
    mNetTrafficAutohide.setOnPreferenceChangeListener(this);
    mNetTrafficAutohideThreshold = (SeekBarPreferenceCham) prefSet.findPreference(NETWORK_TRAFFIC_AUTOHIDE_THRESHOLD);
    int netTrafficAutohideThreshold = Settings.System.getInt(getActivity().getContentResolver(), Settings.System.NETWORK_TRAFFIC_AUTOHIDE_THRESHOLD, 10);
    mNetTrafficAutohideThreshold.setValue(netTrafficAutohideThreshold / 1);
    mNetTrafficAutohideThreshold.setOnPreferenceChangeListener(this);
    mNetTrafficHidearrow = (SwitchPreference) prefSet.findPreference(NETWORK_TRAFFIC_HIDEARROW);
    mNetTrafficHidearrow.setChecked((Settings.System.getInt(getActivity().getContentResolver(), Settings.System.NETWORK_TRAFFIC_HIDEARROW, 0) == 1));
    mNetTrafficHidearrow.setOnPreferenceChangeListener(this);
    mNetTrafficColor = (ColorPickerPreference) prefSet.findPreference(NETWORK_TRAFFIC_COLOR);
    mNetTrafficColor.setOnPreferenceChangeListener(this);
    int intColor = Settings.System.getInt(getActivity().getContentResolver(), Settings.System.NETWORK_TRAFFIC_COLOR, 0xffffffff);
    String hexColor = String.format("#%08x", (0xffffffff & intColor));
    mNetTrafficColor.setSummary(hexColor);
    mNetTrafficColor.setNewPreviewColor(intColor);
    if (TrafficStats.getTotalTxBytes() != TrafficStats.UNSUPPORTED && TrafficStats.getTotalRxBytes() != TrafficStats.UNSUPPORTED) {
        mNetTrafficVal = Settings.System.getInt(getActivity().getContentResolver(), Settings.System.NETWORK_TRAFFIC_STATE, 0);
        int intIndex = mNetTrafficVal & (MASK_UP + MASK_DOWN);
        intIndex = mNetTrafficState.findIndexOfValue(String.valueOf(intIndex));
        updateNetworkTrafficState(intIndex);
        mNetTrafficState.setValueIndex(intIndex >= 0 ? intIndex : 0);
        mNetTrafficState.setSummary(mNetTrafficState.getEntry());
        mNetTrafficState.setOnPreferenceChangeListener(this);
        mNetTrafficUnit.setValueIndex(getBit(mNetTrafficVal, MASK_UNIT) ? 1 : 0);
        mNetTrafficUnit.setSummary(mNetTrafficUnit.getEntry());
        mNetTrafficUnit.setOnPreferenceChangeListener(this);
        intIndex = (mNetTrafficVal & MASK_PERIOD) >>> 16;
        intIndex = mNetTrafficPeriod.findIndexOfValue(String.valueOf(intIndex));
        mNetTrafficPeriod.setValueIndex(intIndex >= 0 ? intIndex : 1);
        mNetTrafficPeriod.setSummary(mNetTrafficPeriod.getEntry());
        mNetTrafficPeriod.setOnPreferenceChangeListener(this);
    }
}
Example 71
Project: PracticeDemo-master  File: DeviceInfoActivty.java View source code
@Override
public boolean handleMessage(Message msg) {
    //�准?...
    ////获�通过Mobile连接收到的字节总数,�包�WiFi
    long mrx = TrafficStats.getMobileRxBytes() / 1024;
    //Mobile��的总字节数
    long mtx = TrafficStats.getMobileTxBytes() / 1024;
    long trx = (long) ((TrafficStats.getTotalRxBytes() - mTotalRxBytes) * 1.00f / 1024);
    //获�总的接�字节数,包�Mobile和WiFi等
    mTotalRxBytes = TrafficStats.getTotalRxBytes();
    //总的��字节数,包�Mobile和WiFi等
    long ttx = TrafficStats.getTotalTxBytes() / 1024;
    //获��个网络UID的接�字节数,�一个进程的总接收�
    long uidrx = TrafficStats.getUidRxBytes(getApplicationInfo().uid) / 1024;
    //获��个网络UID的��字节数,�一个进程的总���
    long uidtx = TrafficStats.getUidTxBytes(getApplicationInfo().uid) / 1024;
    StringBuilder sb = new StringBuilder();
    sb.append("mrx:" + mrx + "\n\r").append("mtx:" + mtx + "\n\r").append("trx:" + trx + "\n\r").append("ttx:" + ttx + "\n\r").append("uidrx:" + uidrx + "\n\r").append("uidtx:" + uidtx + "\n\r");
    mTvDeviceInfo.setText(sb.toString());
    mHandler.sendEmptyMessageDelayed(0, 1000);
    return true;
}
Example 72
Project: RobamVolley-master  File: NetworkDispatcher.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
        try {
            // Take a request from the queue.
            // TODO:是�是当�队列中没有任务,就会阻塞在这里呢?
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            // 原æ?¥è¿™æ˜¯æµ?é‡?统计啊.系统æ??供了一个æµ?é‡?统计的功能,以å?Žå?¯ä»¥ç”¨å’¯
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
            }
            // Perform the network request.�起网络请求
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }
            // 解�数�,调用的是Request中的方法,这个方法开放自定义的.所以�能解�N中数�.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");
            // TODO:尼玛的,翻译读了å??é??æ‰?明白什么æ„?æ€?:对于304ç­‰entireæ•°æ?®æ²¡æœ‰å?˜åŒ–çš„,å?ªæ›´æ–°ç¼“存的metadata而ä¸?是整个记录.
            if (request.shouldCache() && response.cacheEntry != null) {
                // 这里的CacheData就是需�缓存的数�啊.是从自定义的Request.parseNetworkResponse中传递过�的.
                // 所以这就给了一个很大的空间,需�缓存的就写入,�需�就传null
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }
            // Post the response back.
            request.markDelivered();
            // Post�应数�,估计是调用Listener的方法了.
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            mDelivery.postError(request, new VolleyError(e));
        }
    }
}
Example 73
Project: swan_sense_integration-master  File: DataTransmitter.java View source code
@TargetApi(Build.VERSION_CODES.FROYO)
@Override
public void run() {
    // check if the service is (supposed to be) alive before scheduling next alarm
    if (true == ServiceStateHelper.getInstance(mContext).isLoggedIn()) {
        // check if transmission should be started
        ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        //Check battery state
        SharedPreferences mainPrefs = mContext.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);
        //boolean isChargingOnly = mainPrefs.getBoolean(Advanced.IS_CHARGING_ONLY, true);
        String batteryState = mainPrefs.getString(SensePrefs.Main.Advanced.BATTERY, "When battery level above threshold");
        if (0 == batteryState.compareTo("Only when charging")) {
            if (!isCharging()) {
                //if upload should be done only when the device is charging, return
                Log.d(TAG, "device is not charging, transfer delayed");
                return;
            }
        } else if (0 == batteryState.compareTo("When battery level above threshold")) {
            String batteryTshold = mainPrefs.getString(SensePrefs.Main.Advanced.BATTERY_THRESHOLD, "60");
            if (Integer.parseInt(batteryTshold) >= getBatteryLevel()) {
                Log.d(TAG, "device is low on battery, transfer delayed");
                return;
            }
        } else if (0 == batteryState.compareTo("Always")) {
            Log.d(TAG, "Battery state: Always, continue the transfer");
        }
        //Check mobile network
        NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        String mobileNetwork = mainPrefs.getString(SensePrefs.Main.Advanced.MOBILE_NETWORK_UPLOAD, "WiFi");
        if ((0 == mobileNetwork.compareTo("Any") && (wifi.isConnected() || mobile.isConnected())) || (0 == mobileNetwork.compareTo("WiFi") && wifi.isConnected()) || ((0 == mobileNetwork.compareTo("3G") || 0 == mobileNetwork.compareTo("4G") || 0 == mobileNetwork.compareTo("2G")) && mobile.isConnected())) {
            Log.d(TAG, "Starting transmission");
            // start the transmission if we have WiFi connection
            if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) || wifi.isConnected()) {
                if ((SystemClock.elapsedRealtime() - mLastTxTime >= mTxInterval)) {
                    transmissionService();
                }
            } else {
                // if there is no WiFi connection, postpone the transmission
                mLastTxBytes = TrafficStats.getMobileTxBytes() - mTxBytes;
                mTxBytes = TrafficStats.getMobileTxBytes();
                if ((SystemClock.elapsedRealtime() - mLastTxTime >= ADAPTIVE_TX_INTERVAL)) {
                    transmissionService();
                } else // if any transmission took place recently, use the tail to transmit the sensor data
                if ((mLastTxBytes >= 500) && (SystemClock.elapsedRealtime() - mLastTxTime >= ADAPTIVE_TX_INTERVAL - (long) (ADAPTIVE_TX_INTERVAL * 0.2))) {
                    transmissionService();
                } else {
                // do nothing
                }
            }
        } else {
            Log.d(TAG, "Mobile network invalid, transfer delayed");
            return;
        }
    } else {
        Log.d(TAG, "skip transmission: Sense service is not logged in");
    // skip transmission: Sense service is not logged in
    }
}
Example 74
Project: packages_apps_settings-master  File: RadioInfo.java View source code
private final void updateDataStats2() {
    Resources r = getResources();
    long txPackets = TrafficStats.getMobileTxPackets();
    long rxPackets = TrafficStats.getMobileRxPackets();
    long txBytes = TrafficStats.getMobileTxBytes();
    long rxBytes = TrafficStats.getMobileRxBytes();
    String packets = r.getString(R.string.radioInfo_display_packets);
    String bytes = r.getString(R.string.radioInfo_display_bytes);
    sent.setText(txPackets + " " + packets + ", " + txBytes + " " + bytes);
    received.setText(rxPackets + " " + packets + ", " + rxBytes + " " + bytes);
}
Example 75
Project: Cangol-appcore-master  File: StatsTraffic.java View source code
private void addAppTrafficStats(int uid, String packageName) {
    AppTraffic appTraffic = new AppTraffic();
    appTraffic.uid = uid;
    appTraffic.packageName = packageName;
    appTraffic.totalRx = TrafficStats.getUidRxBytes(uid);
    appTraffic.totalTx = TrafficStats.getUidTxBytes(uid);
    appTraffic.mobileRx = 0;
    appTraffic.mobileTx = 0;
    appTraffic.wifiRx = 0;
    appTraffic.wifiTx = 0;
    trafficDbService.saveAppTraffic(appTraffic);
}
Example 76
Project: platform_external_apache-http-master  File: SingleClientConnManager.java View source code
/**
     * Obtains a connection.
     * This method does not block.
     *
     * @param route     where the connection should point to
     *
     * @return  a connection that can be used to communicate
     *          along the given route
     */
public ManagedClientConnection getConnection(HttpRoute route, Object state) {
    if (route == null) {
        throw new IllegalArgumentException("Route may not be null.");
    }
    assertStillUp();
    if (log.isDebugEnabled()) {
        log.debug("Get connection for route " + route);
    }
    if (managedConn != null)
        revokeConnection();
    // check re-usability of the connection
    boolean recreate = false;
    boolean shutdown = false;
    // Kill the connection if it expired.
    closeExpiredConnections();
    if (uniquePoolEntry.connection.isOpen()) {
        RouteTracker tracker = uniquePoolEntry.tracker;
        shutdown = (// can happen if method is aborted
        tracker == null || !tracker.toRoute().equals(route));
    } else {
        // If the connection is not open, create a new PoolEntry,
        // as the connection may have been marked not reusable,
        // due to aborts -- and the PoolEntry should not be reused
        // either.  There's no harm in recreating an entry if
        // the connection is closed.
        recreate = true;
    }
    if (shutdown) {
        recreate = true;
        try {
            uniquePoolEntry.shutdown();
        } catch (IOException iox) {
            log.debug("Problem shutting down connection.", iox);
        }
    }
    if (recreate)
        uniquePoolEntry = new PoolEntry();
    // updated statistics options.
    try {
        final Socket socket = uniquePoolEntry.connection.getSocket();
        if (socket != null) {
            TrafficStats.tagSocket(socket);
        }
    } catch (IOException iox) {
        log.debug("Problem tagging socket.", iox);
    }
    // END android-changed
    managedConn = new ConnAdapter(uniquePoolEntry, route);
    return managedConn;
}
Example 77
Project: android-15-master  File: WifiService.java View source code
private void notifyOnDataActivity() {
    long sent, received;
    long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
    int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
    mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
    mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
    if (preTxPkts > 0 || preRxPkts > 0) {
        sent = mTxPkts - preTxPkts;
        received = mRxPkts - preRxPkts;
        if (sent > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
        }
        if (received > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_IN;
        }
        if (dataActivity != mDataActivity && !mScreenOff) {
            mDataActivity = dataActivity;
            for (AsyncChannel client : mClients) {
                client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
            }
        }
    }
}
Example 78
Project: BetterWifiOnOff-master  File: WifiControl.java View source code
// alternative: parse /proc/net/xt_qtaguid/iface_stat_all (entry wlan0) at two times and determine the rate 
@TargetApi(8)
public static void snapshot(Context ctx) {
    long snapshotTotalTimestamp = SystemClock.elapsedRealtime();
    long snapshotTotalBytes = 0;
    if (TrafficStats.getTotalRxBytes() != TrafficStats.UNSUPPORTED) {
        snapshotTotalBytes = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
    } else {
        snapshotTotalBytes = 0;
    }
    Log.i(TAG, "Snapshot at " + DateUtils.now() + ": " + snapshotTotalBytes + " Bytes");
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    SharedPreferences.Editor editor = sharedPrefs.edit();
    editor.putLong("snapshot_time", snapshotTotalTimestamp);
    editor.putLong("snapshot_bytes", snapshotTotalBytes);
    editor.commit();
}
Example 79
Project: grpc-java-master  File: Platform.java View source code
/** Attempt to match the host runtime to a capable Platform implementation. */
private static Platform findPlatform() {
    Provider sslProvider = GrpcUtil.IS_RESTRICTED_APPENGINE ? getAppEngineProvider() : getAndroidSecurityProvider();
    if (sslProvider != null) {
        // Attempt to find Android 2.3+ APIs.
        OptionalMethod<Socket> setUseSessionTickets = new OptionalMethod<Socket>(null, "setUseSessionTickets", boolean.class);
        OptionalMethod<Socket> setHostname = new OptionalMethod<Socket>(null, "setHostname", String.class);
        Method trafficStatsTagSocket = null;
        Method trafficStatsUntagSocket = null;
        OptionalMethod<Socket> getAlpnSelectedProtocol = new OptionalMethod<Socket>(byte[].class, "getAlpnSelectedProtocol");
        OptionalMethod<Socket> setAlpnProtocols = new OptionalMethod<Socket>(null, "setAlpnProtocols", byte[].class);
        // Attempt to find Android 4.0+ APIs.
        try {
            Class<?> trafficStats = Class.forName("android.net.TrafficStats");
            trafficStatsTagSocket = trafficStats.getMethod("tagSocket", Socket.class);
            trafficStatsUntagSocket = trafficStats.getMethod("untagSocket", Socket.class);
        } catch (ClassNotFoundException ignored) {
        } catch (NoSuchMethodException ignored) {
        }
        return new Android(setUseSessionTickets, setHostname, trafficStatsTagSocket, trafficStatsUntagSocket, getAlpnSelectedProtocol, setAlpnProtocols, sslProvider);
    }
    try {
        sslProvider = SSLContext.getDefault().getProvider();
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException(nsae);
    }
    // Find Jetty's ALPN extension for OpenJDK.
    try {
        String negoClassName = "org.eclipse.jetty.alpn.ALPN";
        Class<?> negoClass = Class.forName(negoClassName);
        Class<?> providerClass = Class.forName(negoClassName + "$Provider");
        Class<?> clientProviderClass = Class.forName(negoClassName + "$ClientProvider");
        Class<?> serverProviderClass = Class.forName(negoClassName + "$ServerProvider");
        Method putMethod = negoClass.getMethod("put", SSLSocket.class, providerClass);
        Method getMethod = negoClass.getMethod("get", SSLSocket.class);
        Method removeMethod = negoClass.getMethod("remove", SSLSocket.class);
        return new JdkWithJettyBootPlatform(putMethod, getMethod, removeMethod, clientProviderClass, serverProviderClass, sslProvider);
    } catch (ClassNotFoundException ignored) {
    } catch (NoSuchMethodException ignored) {
    }
    return new Platform(sslProvider);
}
Example 80
Project: GT-master  File: NetUtils.java View source code
/**
	 * 根�进程id获�网络����
	 * 
	 * @return 字节数
	 */
public static long getOutOctets(String pName) {
    int uid = ProcessUtils.getProcessUID(pName);
    String netPath = "/proc/uid_stat/" + uid + "/tcp_snd";
    switch(netCase) {
        case TYPE_CASE1:
            File f = new File(netPath);
            if (!f.exists()) {
                // 转方案2
                netCase = TYPE_CASE2;
            } else {
                String ret = "0";
                try {
                    FileReader fr = new FileReader(netPath);
                    BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
                    ret = localBufferedReader.readLine();
                    FileUtil.closeReader(localBufferedReader);
                    return Long.parseLong(ret);
                } catch (Exception e) {
                    netCase = TYPE_CASE2;
                }
                // 最�一个�试
                if ((ret == null || ret.equals("0")) && (TrafficStats.getUidTxBytes(uid) > 0 || TrafficStats.getUidRxBytes(uid) > 0)) {
                    netCase = TYPE_CASE2;
                }
            }
        case TYPE_CASE2:
            long s = TrafficStats.getUidTxBytes(uid);
            if (s >= 0) {
                return s;
            }
            netCase = TYPE_CASE3;
        case TYPE_CASE3:
        default:
            break;
    }
    return 0;
}
Example 81
Project: life-master  File: NetworkDispatcher.java View source code
/*
     * 使用 Android 4.0 以�,DDMS 中的 Network Traffic Tool
     *
     * 这里为 NetworkDispatcher 的打上 Traffic 的 tag
     * 实时地监测网络的使用情况
     */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
    // Tag the request (if API >= 14)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        /*
             * 设置 该线程 的 监测网络的使用情况
             * 在 Network Traffic Tool 工具中查到
             */
        TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
    }
}
Example 82
Project: okhttp-utils-master  File: Platform.java View source code
/** Attempt to match the host runtime to a capable Platform implementation. */
private static Platform findPlatform() {
    // Attempt to find Android 2.3+ APIs.
    try {
        try {
            Class.forName("com.android.org.conscrypt.OpenSSLSocketImpl");
        } catch (ClassNotFoundException e) {
            Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl");
        }
        OptionalMethod<Socket> setUseSessionTickets = new OptionalMethod<>(null, "setUseSessionTickets", boolean.class);
        OptionalMethod<Socket> setHostname = new OptionalMethod<>(null, "setHostname", String.class);
        Method trafficStatsTagSocket = null;
        Method trafficStatsUntagSocket = null;
        OptionalMethod<Socket> getAlpnSelectedProtocol = null;
        OptionalMethod<Socket> setAlpnProtocols = null;
        // Attempt to find Android 4.0+ APIs.
        try {
            Class<?> trafficStats = Class.forName("android.net.TrafficStats");
            trafficStatsTagSocket = trafficStats.getMethod("tagSocket", Socket.class);
            trafficStatsUntagSocket = trafficStats.getMethod("untagSocket", Socket.class);
            // Attempt to find Android 5.0+ APIs.
            try {
                // Arbitrary class added in Android 5.0.
                Class.forName("android.net.Network");
                getAlpnSelectedProtocol = new OptionalMethod<>(byte[].class, "getAlpnSelectedProtocol");
                setAlpnProtocols = new OptionalMethod<>(null, "setAlpnProtocols", byte[].class);
            } catch (ClassNotFoundException ignored) {
            }
        } catch (ClassNotFoundExceptionNoSuchMethodException |  ignored) {
        }
        return new Android(setUseSessionTickets, setHostname, trafficStatsTagSocket, trafficStatsUntagSocket, getAlpnSelectedProtocol, setAlpnProtocols);
    } catch (ClassNotFoundException ignored) {
    }
    // Find Jetty's ALPN extension for OpenJDK.
    try {
        String negoClassName = "org.eclipse.jetty.alpn.ALPN";
        Class<?> negoClass = Class.forName(negoClassName);
        Class<?> providerClass = Class.forName(negoClassName + "$Provider");
        Class<?> clientProviderClass = Class.forName(negoClassName + "$ClientProvider");
        Class<?> serverProviderClass = Class.forName(negoClassName + "$ServerProvider");
        Method putMethod = negoClass.getMethod("put", SSLSocket.class, providerClass);
        Method getMethod = negoClass.getMethod("get", SSLSocket.class);
        Method removeMethod = negoClass.getMethod("remove", SSLSocket.class);
        return new JdkWithJettyBootPlatform(putMethod, getMethod, removeMethod, clientProviderClass, serverProviderClass);
    } catch (ClassNotFoundExceptionNoSuchMethodException |  ignored) {
    }
    return new Platform();
}
Example 83
Project: SwipeCardsView-master  File: Platform.java View source code
/** Attempt to match the host runtime to a capable Platform implementation. */
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.KITKAT)
private static Platform findPlatform() {
    // Attempt to find Android 2.3+ APIs.
    try {
        try {
            Class.forName("com.android.org.conscrypt.OpenSSLSocketImpl");
        } catch (ClassNotFoundException e) {
            Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl");
        }
        OptionalMethod<Socket> setUseSessionTickets = new OptionalMethod<>(null, "setUseSessionTickets", boolean.class);
        OptionalMethod<Socket> setHostname = new OptionalMethod<>(null, "setHostname", String.class);
        Method trafficStatsTagSocket = null;
        Method trafficStatsUntagSocket = null;
        OptionalMethod<Socket> getAlpnSelectedProtocol = null;
        OptionalMethod<Socket> setAlpnProtocols = null;
        // Attempt to find Android 4.0+ APIs.
        try {
            Class<?> trafficStats = Class.forName("android.net.TrafficStats");
            trafficStatsTagSocket = trafficStats.getMethod("tagSocket", Socket.class);
            trafficStatsUntagSocket = trafficStats.getMethod("untagSocket", Socket.class);
            // Attempt to find Android 5.0+ APIs.
            try {
                // Arbitrary class added in Android 5.0.
                Class.forName("android.net.Network");
                getAlpnSelectedProtocol = new OptionalMethod<>(byte[].class, "getAlpnSelectedProtocol");
                setAlpnProtocols = new OptionalMethod<>(null, "setAlpnProtocols", byte[].class);
            } catch (ClassNotFoundException ignored) {
            }
        } catch (ClassNotFoundExceptionNoSuchMethodException |  ignored) {
        }
        return new Android(setUseSessionTickets, setHostname, trafficStatsTagSocket, trafficStatsUntagSocket, getAlpnSelectedProtocol, setAlpnProtocols);
    } catch (ClassNotFoundException ignored) {
    }
    // Find Jetty's ALPN extension for OpenJDK.
    try {
        String negoClassName = "org.eclipse.jetty.alpn.ALPN";
        Class<?> negoClass = Class.forName(negoClassName);
        Class<?> providerClass = Class.forName(negoClassName + "$Provider");
        Class<?> clientProviderClass = Class.forName(negoClassName + "$ClientProvider");
        Class<?> serverProviderClass = Class.forName(negoClassName + "$ServerProvider");
        Method putMethod = negoClass.getMethod("put", SSLSocket.class, providerClass);
        Method getMethod = negoClass.getMethod("get", SSLSocket.class);
        Method removeMethod = negoClass.getMethod("remove", SSLSocket.class);
        return new JdkWithJettyBootPlatform(putMethod, getMethod, removeMethod, clientProviderClass, serverProviderClass);
    } catch (ClassNotFoundExceptionNoSuchMethodException |  ignored) {
    }
    return new Platform();
}
Example 84
Project: packages-apps-Email-master  File: ImapService.java View source code
/**
     * Start foreground synchronization of the specified folder. This is called by
     * synchronizeMailbox or checkMail.
     * TODO this should use ID's instead of fully-restored objects
     * @return The status code for whether this operation succeeded.
     * @throws MessagingException
     */
public static synchronized int synchronizeMailboxSynchronous(Context context, final Account account, final Mailbox folder, final boolean loadMore, final boolean uiRefresh) throws MessagingException {
    TrafficStats.setThreadStatsTag(TrafficFlags.getSyncFlags(context, account));
    final NotificationController nc = NotificationControllerCreatorHolder.getInstance(context);
    Store remoteStore = null;
    try {
        remoteStore = Store.getInstance(account, context);
        processPendingActionsSynchronous(context, account, remoteStore, uiRefresh);
        synchronizeMailboxGeneric(context, account, remoteStore, folder, loadMore, uiRefresh);
        // Clear authentication notification for this account
        nc.cancelLoginFailedNotification(account.mId);
    } catch (MessagingException e) {
        if (Logging.LOGD) {
            LogUtils.d(Logging.LOG_TAG, "synchronizeMailboxSynchronous", e);
        }
        if (e instanceof AuthenticationFailedException) {
            nc.showLoginFailedNotificationSynchronous(account.mId, true);
        }
        throw e;
    } finally {
        if (remoteStore != null) {
            remoteStore.closeConnections();
        }
    }
    // correctly in caller.
    return EmailServiceStatus.SUCCESS;
}
Example 85
Project: platform_packages_apps_email-master  File: ImapService.java View source code
/**
     * Start foreground synchronization of the specified folder. This is called by
     * synchronizeMailbox or checkMail.
     * TODO this should use ID's instead of fully-restored objects
     * @return The status code for whether this operation succeeded.
     * @throws MessagingException
     */
public static synchronized int synchronizeMailboxSynchronous(Context context, final Account account, final Mailbox folder, final boolean loadMore, final boolean uiRefresh) throws MessagingException {
    TrafficStats.setThreadStatsTag(TrafficFlags.getSyncFlags(context, account));
    final NotificationController nc = NotificationControllerCreatorHolder.getInstance(context);
    Store remoteStore = null;
    try {
        remoteStore = Store.getInstance(account, context);
        processPendingActionsSynchronous(context, account, remoteStore, uiRefresh);
        synchronizeMailboxGeneric(context, account, remoteStore, folder, loadMore, uiRefresh);
        // Clear authentication notification for this account
        nc.cancelLoginFailedNotification(account.mId);
    } catch (MessagingException e) {
        if (Logging.LOGD) {
            LogUtils.d(Logging.LOG_TAG, "synchronizeMailboxSynchronous", e);
        }
        if (e instanceof AuthenticationFailedException) {
            nc.showLoginFailedNotificationSynchronous(account.mId, true);
        }
        throw e;
    } finally {
        if (remoteStore != null) {
            remoteStore.closeConnections();
        }
    }
    // correctly in caller.
    return EmailServiceStatus.SUCCESS;
}
Example 86
Project: PowerDoctor-master  File: OSMonitorService.java View source code
@Override
public void run() {
    double mWifiPower = 0.0;
    int bright_level = 0;
    cpuLoad = JNILibrary.GetCPUUsageValue();
    if (cpuLoad < 20)
        serviceNotify.iconLevel = 1 + useColor * 100;
    else if (cpuLoad < 40)
        serviceNotify.iconLevel = 2 + useColor * 100;
    else if (cpuLoad < 60)
        serviceNotify.iconLevel = 3 + useColor * 100;
    else if (cpuLoad < 80)
        serviceNotify.iconLevel = 4 + useColor * 100;
    else if (cpuLoad < 100)
        serviceNotify.iconLevel = 5 + useColor * 100;
    else
        serviceNotify.iconLevel = 6 + useColor * 100;
    //java proc/stat
    mOCpuUsage.readStats();
    //notification� 표시하는 정보들� 기�한다.
    String maininfo = "CPU: " + cpuLoad + "% , " + mOCpuUsage.getTotalCPUInt() + "%, " + "MEM:" + MemoryFormat.format(JNILibrary.GetMemBuffer() + JNILibrary.GetMemCached() + JNILibrary.GetMemFree()) + "K";
    String extendinfo = "";
    if (useCelsius)
        extendinfo = " Battery: " + battLevel + "%" + " (" + temperature / 10 + "°C)";
    else
        extendinfo = " Battery: " + battLevel + "%" + " (" + ((int) temperature / 10 * 9 / 5 + 32) + "°F)";
    serviceNotify.setLatestEventInfo(serviceContext, maininfo, extendinfo, serviceNotify.contentIntent);
    /* 기존 소스 주�임 제거시 �러 발�. 
				serviceNotify.contentView.setTextViewText(R.id.StatusBarCPU, "CPU: "+cpuLoad+"%");
				serviceNotify.contentView.setTextViewText(R.id.StatusBarMEM, "MEM: "+MemoryFormat.format(JNILibrary.GetMemBuffer()+JNILibrary.GetMemCached()+JNILibrary.GetMemFree())+ "K");

				if(useCelsius)
					serviceNotify.contentView.setTextViewText(R.id.StatusBarBAT, "BAT: "+battLevel+"%"+" ("+temperature/10+"°C)");
				else
					serviceNotify.contentView.setTextViewText(R.id.StatusBarBAT, "BAT: "+battLevel+"%"+" ("+((int)temperature/10*9/5+32)+"°F)");
				*/
    //App-Widget� 대한 �작 부분� 설정한다.
    //출력할 내뇽� RemoteViews로 만들어서 관리��게 전달해야 Widget� 갱신�어 진다.
    RemoteViews views = new RemoteViews(serviceContext.getPackageName(), R.layout.battery_widget);
    views.setTextViewText(R.id.gauge, "" + cpuLoad);
    AppWidgetManager wm = AppWidgetManager.getInstance(OSMonitorService.this);
    ComponentName widget = new ComponentName(serviceContext, BatteryWidget.class);
    wm.updateAppWidget(widget, views);
    try {
        serviceNM.notify(NOTIFYID, serviceNotify);
    } catch (Exception e) {
    }
    //스�린 여부�따� 연산� �용시킬 껀지를 �별 한다. 
    if (mPowermanager.isScreenOn()) {
        LedOn = 1.0;
        bright_level = Settings.System.getInt(mContentResolver, Settings.System.SCREEN_BRIGHTNESS, -1);
    } else {
        LedOn = 0.0;
    }
    //Wifi Interface가 활성화 �태�지 부터 체� 한다. 
    if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
        mPowerModel.mWIFITActivityTime++;
        long transmitPackets = TrafficStats.getTotalTxPackets();
        long receivePackets = TrafficStats.getTotalRxPackets();
        long lastPackets = receivePackets + transmitPackets - lastReceivePackets - lastTransmitPackets;
        //chunk� packet Rate를 누� 시킨다.
        //� 패킷� 누� 시킨다.
        mPowerModel.mWIFIPacketRate += lastPackets;
        //표준편차를 계산하기 위함 �다. 
        mPowerModel.mSDWiFiPacketRate.add((double) lastPackets);
        //wifi Power 정보를 계산한다.
        if (lastPackets >= mOPowerModelValue.mWifiMaxCondition) {
            mWifiPower = mOPowerModelValue.mWifiMax;
        } else {
            mWifiPower = mOPowerModelValue.mWiFiOn + lastPackets * mOPowerModelValue.mWiFiModel_B + Math.pow(lastPackets, 2) * mOPowerModelValue.mWiFiModel_A;
        }
        //Packets 정보를 갱신 한다. 
        lastTransmitPackets = transmitPackets;
        lastReceivePackets = receivePackets;
    }
    //Power Model 연산� 한다.
    /*				mOPowerModelValue.mCurrentPower_typeFour.add(
						LedOn * mOPowerModelValue.mBrightCoeff*bright_level + mOPowerModelValue.mBrightConst + 
						mOPowerModelValue.mCPUUageMulTypeFour*JNILibrary.GetCPUUsageValue() +
						mOPowerModelValue.mCPUUageSumTypeFour +
						mWifiPower);*/
    mPowerValue.add(LedOn * mOPowerModelValue.mBrightCoeff * bright_level + mOPowerModelValue.mBrightConst + mOPowerModelValue.mCPUUageMulTypeFour * JNILibrary.GetCPUUsageValue() + mOPowerModelValue.mCPUUageSumTypeFour + mWifiPower);
    //current Sensor와 비�하기 위한 루틴 50초마다 �균� 내어주기 위함 �다. 
    /*AverageConditionBit++;
				if(AverageConditionBit >= 50){
					double sumFour = 0.0;
					double avgFour = 0.0;
					for(int i =0; i<mOPowerModelValue.mCurrentPower_typeFour.size(); i++){
						sumFour += mOPowerModelValue.mCurrentPower_typeFour.get(i);
					}
					avgFour = sumFour / 50.0;		
					mPowerValue.add(avgFour);
					
					//초기화 루틴
					AverageConditionBit = 0 ;
					mOPowerModelValue.CurrentPowerClear(); //다시 power값� 줙 시켜야 하므로
				}*/
    mHandler.postDelayed(mRefresh, UpdateInterval * 1000);
}
Example 87
Project: android_frameworks_base_telephony-master  File: GsmDataConnectionTracker.java View source code
public void run() {
    long sent, received;
    long preTxPkts = -1, preRxPkts = -1;
    Activity newActivity;
    preTxPkts = txPkts;
    preRxPkts = rxPkts;
    txPkts = TrafficStats.getMobileTxPackets();
    rxPkts = TrafficStats.getMobileRxPackets();
    if (netStatPollEnabled && (preTxPkts > 0 || preRxPkts > 0)) {
        sent = txPkts - preTxPkts;
        received = rxPkts - preRxPkts;
        if (sent > 0 && received > 0) {
            sentSinceLastRecv = 0;
            newActivity = Activity.DATAINANDOUT;
            mPdpResetCount = 0;
        } else if (sent > 0 && received == 0) {
            if (phone.getState() == Phone.State.IDLE) {
                sentSinceLastRecv += sent;
            } else {
                sentSinceLastRecv = 0;
            }
            newActivity = Activity.DATAOUT;
        } else if (sent == 0 && received > 0) {
            sentSinceLastRecv = 0;
            newActivity = Activity.DATAIN;
            mPdpResetCount = 0;
        } else if (sent == 0 && received == 0) {
            newActivity = Activity.NONE;
        } else {
            sentSinceLastRecv = 0;
            newActivity = Activity.NONE;
        }
        if (activity != newActivity && mIsScreenOn) {
            activity = newActivity;
            phone.notifyDataActivity();
        }
    }
    int watchdogTrigger = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT, NUMBER_SENT_PACKETS_OF_HANG);
    if (sentSinceLastRecv >= watchdogTrigger) {
        // we already have NUMBER_SENT_PACKETS sent without ack
        if (mNoRecvPollCount == 0) {
            EventLog.writeEvent(EventLogTags.PDP_RADIO_RESET_COUNTDOWN_TRIGGERED, sentSinceLastRecv);
        }
        int noRecvPollLimit = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT, NO_RECV_POLL_LIMIT);
        if (mNoRecvPollCount < noRecvPollLimit) {
            // Start polling the context list in an attempt to recover.
            if (DBG)
                log("no DATAIN in a while; polling PDP");
            phone.mCM.getDataCallList(obtainMessage(EVENT_GET_PDP_LIST_COMPLETE));
            mNoRecvPollCount++;
            // Slow down the poll interval to let things happen
            netStatPollPeriod = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_ERROR_POLL_INTERVAL_MS, POLL_NETSTAT_SLOW_MILLIS);
        } else {
            if (DBG)
                log("Sent " + String.valueOf(sentSinceLastRecv) + " pkts since last received");
            // We've exceeded the threshold.  Run ping test as a final check;
            // it will proceed with recovery if ping fails.
            stopNetStatPoll();
            Thread pingTest = new Thread() {

                public void run() {
                    runPingTest();
                }
            };
            mPingTestActive = true;
            pingTest.start();
        }
    } else {
        mNoRecvPollCount = 0;
        if (mIsScreenOn) {
            netStatPollPeriod = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS);
        } else {
            netStatPollPeriod = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS, POLL_NETSTAT_SCREEN_OFF_MILLIS);
        }
    }
    if (netStatPollEnabled) {
        mDataConnectionTracker.postDelayed(this, netStatPollPeriod);
    }
}
Example 88
Project: download-manager-master  File: DownloadTask.java View source code
private void runInternal() {
    // Skip when download already marked as finished; this download was probably started again while racing with UpdateThread.
    int downloadStatus = downloadsRepository.getDownloadStatus(originalDownloadInfo.getId());
    if (downloadStatus == DownloadStatus.SUCCESS) {
        LLog.d("Download " + originalDownloadInfo.getId() + " already finished; skipping");
        return;
    }
    if (DownloadStatus.isCancelled(downloadStatus)) {
        LLog.d("Download " + originalDownloadInfo.getId() + " already cancelled; skipping");
        return;
    }
    if (DownloadStatus.isError(downloadStatus)) {
        LLog.d("Download " + originalDownloadInfo.getId() + " already failed: status = " + downloadStatus + "; skipping");
        return;
    }
    if (DownloadStatus.isDeleting(downloadStatus)) {
        LLog.d("Download " + originalDownloadInfo.getId() + " is deleting: status = " + downloadStatus + "; skipping");
        return;
    }
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloadStatus.UNKNOWN_ERROR;
    int numFailed = originalDownloadInfo.getNumFailed();
    String errorMsg = null;
    State state = new State(originalDownloadInfo);
    try {
        checkDownloadCanProceed();
        if (downloadStatus != DownloadStatus.RUNNING) {
            downloadsRepository.setDownloadRunning(originalDownloadInfo);
            updateBatchStatus(originalDownloadInfo.getBatchId(), originalDownloadInfo.getId());
        }
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();
        LLog.i("Download " + originalDownloadInfo.getId() + " starting");
        // Remember which network this download started on; used to
        // determine if errors were due to network changes.
        // Param downloadInfo.uid removed TODO
        final NetworkInfo networkInfo = systemFacade.getActiveNetworkInfo();
        if (networkInfo != null) {
            state.networkType = networkInfo.getType();
        }
        // Network traffic on this thread should be counted against the
        // requesting UID, and is tagged with well-known value.
        // TrafficStats.TAG_SYSTEM_DOWNLOAD
        TrafficStats.setThreadStatsTag(0xFFFFFF01);
        try {
            // TODO: migrate URL sanity checking into client side of API
            state.url = new URL(state.requestUri);
        } catch (MalformedURLException e) {
            throw new StopRequestException(DownloadStatus.BAD_REQUEST, e);
        }
        executeDownload(state);
        finalizeDestinationFile(state);
        finalStatus = DownloadStatus.SUCCESS;
    } catch (StopRequestException error) {
        errorMsg = error.getMessage();
        String msg = "Aborting request for download " + originalDownloadInfo.getId() + ": " + errorMsg;
        LLog.w(msg, error);
        finalStatus = error.getFinalStatus();
        if (finalStatus == DownloadStatus.WAITING_TO_RETRY) {
            throw new IllegalStateException("Execution should always throw final error codes");
        }
        if (isStatusRetryable(finalStatus)) {
            if (state.gotData) {
                numFailed = 1;
            } else {
                numFailed += 1;
            }
            if (numFailed < Constants.MAX_RETRIES && finalStatus != QUEUED_DUE_CLIENT_RESTRICTIONS) {
                final NetworkInfo info = systemFacade.getActiveNetworkInfo();
                if (info != null && info.getType() == state.networkType && info.isConnected()) {
                    finalStatus = DownloadStatus.WAITING_TO_RETRY;
                } else {
                    finalStatus = DownloadStatus.WAITING_FOR_NETWORK;
                }
            }
        }
    } catch (Throwable ex) {
        errorMsg = ex.getMessage();
        String msg = "Exception for id " + originalDownloadInfo.getId() + ": " + errorMsg;
        LLog.w(msg, ex);
        finalStatus = DownloadStatus.UNKNOWN_ERROR;
    } finally {
        TrafficStats.clearThreadStatsTag();
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(state, finalStatus, errorMsg, numFailed);
        hackToForceClientsRefreshRulesIfConnectionDropped(finalStatus);
        LLog.i("Download " + originalDownloadInfo.getId() + " finished with status " + DownloadStatus.statusToString(finalStatus));
        if (wakeLock != null) {
            wakeLock.release();
        }
    }
    storageManager.incrementNumDownloadsSoFar();
}
Example 89
Project: folio100_frameworks_base-master  File: BatteryStatsImpl.java View source code
public void doUnplug(long batteryUptime, long batteryRealtime) {
    for (int iu = mUidStats.size() - 1; iu >= 0; iu--) {
        Uid u = mUidStats.valueAt(iu);
        u.mStartedTcpBytesReceived = TrafficStats.getUidRxBytes(u.mUid);
        u.mStartedTcpBytesSent = TrafficStats.getUidTxBytes(u.mUid);
        u.mTcpBytesReceivedAtLastUnplug = u.mCurrentTcpBytesReceived;
        u.mTcpBytesSentAtLastUnplug = u.mCurrentTcpBytesSent;
    }
    for (int i = mUnpluggables.size() - 1; i >= 0; i--) {
        mUnpluggables.get(i).unplug(batteryUptime, batteryRealtime);
    }
    // Track total mobile data
    doDataUnplug(mMobileDataRx, TrafficStats.getMobileRxBytes());
    doDataUnplug(mMobileDataTx, TrafficStats.getMobileTxBytes());
    doDataUnplug(mTotalDataRx, TrafficStats.getTotalRxBytes());
    doDataUnplug(mTotalDataTx, TrafficStats.getTotalTxBytes());
    // Track radio awake time
    mRadioDataStart = getCurrentRadioDataUptime();
    mRadioDataUptime = 0;
    // Track bt headset ping count
    mBluetoothPingStart = getCurrentBluetoothPingCount();
    mBluetoothPingCount = 0;
}
Example 90
Project: platform_packages_providers_downloadprovider-master  File: DownloadThread.java View source code
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    // probably started again while racing with UpdateThread.
    if (mInfo.queryDownloadStatus() == Downloads.Impl.STATUS_SUCCESS) {
        logDebug("Already finished; skipping");
        return;
    }
    try {
        // while performing download, register for rules updates
        mNetworkPolicy.registerListener(mPolicyListener);
        logDebug("Starting");
        mInfoDelta.mStatus = STATUS_RUNNING;
        mInfoDelta.writeToDatabase();
        // If we're showing a foreground notification for the requesting
        // app, the download isn't affected by the blocked status of the
        // requesting app
        mIgnoreBlocked = mInfo.isVisible();
        // Use the caller's default network to make this connection, since
        // they might be subject to restrictions that we shouldn't let them
        // circumvent
        mNetwork = mSystemFacade.getActiveNetwork(mInfo.mUid, mIgnoreBlocked);
        if (mNetwork == null) {
            throw new StopRequestException(STATUS_WAITING_FOR_NETWORK, "No network associated with requesting UID");
        }
        // Remember which network this download started on; used to
        // determine if errors were due to network changes.
        final NetworkInfo info = mSystemFacade.getNetworkInfo(mNetwork, mInfo.mUid, mIgnoreBlocked);
        if (info != null) {
            mNetworkType = info.getType();
        }
        // Network traffic on this thread should be counted against the
        // requesting UID, and is tagged with well-known value.
        TrafficStats.setThreadStatsTag(TrafficStats.TAG_SYSTEM_DOWNLOAD);
        TrafficStats.setThreadStatsUid(mInfo.mUid);
        executeDownload();
        mInfoDelta.mStatus = STATUS_SUCCESS;
        TrafficStats.incrementOperationCount(1);
        // If we just finished a chunked file, record total size
        if (mInfoDelta.mTotalBytes == -1) {
            mInfoDelta.mTotalBytes = mInfoDelta.mCurrentBytes;
        }
    } catch (StopRequestException e) {
        mInfoDelta.mStatus = e.getFinalStatus();
        mInfoDelta.mErrorMsg = e.getMessage();
        logWarning("Stop requested with status " + Downloads.Impl.statusToString(mInfoDelta.mStatus) + ": " + mInfoDelta.mErrorMsg);
        if (mInfoDelta.mStatus == STATUS_WAITING_TO_RETRY) {
            throw new IllegalStateException("Execution should always throw final error codes");
        }
        if (isStatusRetryable(mInfoDelta.mStatus)) {
            if (mMadeProgress) {
                mInfoDelta.mNumFailed = 1;
            } else {
                mInfoDelta.mNumFailed += 1;
            }
            if (mInfoDelta.mNumFailed < Constants.MAX_RETRIES) {
                final NetworkInfo info = mSystemFacade.getNetworkInfo(mNetwork, mInfo.mUid, mIgnoreBlocked);
                if (info != null && info.getType() == mNetworkType && info.isConnected()) {
                    mInfoDelta.mStatus = STATUS_WAITING_TO_RETRY;
                } else {
                    mInfoDelta.mStatus = STATUS_WAITING_FOR_NETWORK;
                }
                if ((mInfoDelta.mETag == null && mMadeProgress) || DownloadDrmHelper.isDrmConvertNeeded(mInfoDelta.mMimeType)) {
                    mInfoDelta.mStatus = STATUS_CANNOT_RESUME;
                }
            }
        }
        if (mInfoDelta.mStatus == STATUS_WAITING_FOR_NETWORK && !mInfo.isMeteredAllowed(mInfoDelta.mTotalBytes)) {
            mInfoDelta.mStatus = STATUS_QUEUED_FOR_WIFI;
        }
    } catch (Throwable t) {
        mInfoDelta.mStatus = STATUS_UNKNOWN_ERROR;
        mInfoDelta.mErrorMsg = t.toString();
        logError("Failed: " + mInfoDelta.mErrorMsg, t);
    } finally {
        logDebug("Finished with status " + Downloads.Impl.statusToString(mInfoDelta.mStatus));
        mNotifier.notifyDownloadSpeed(mId, 0);
        finalizeDestination();
        mInfoDelta.writeToDatabase();
        TrafficStats.clearThreadStatsTag();
        TrafficStats.clearThreadStatsUid();
        mNetworkPolicy.unregisterListener(mPolicyListener);
    }
    if (Downloads.Impl.isStatusCompleted(mInfoDelta.mStatus)) {
        if (mInfo.shouldScanFile(mInfoDelta.mStatus)) {
            DownloadScanner.requestScanBlocking(mContext, mInfo.mId, mInfoDelta.mFileName, mInfoDelta.mMimeType);
        }
    } else if (mInfoDelta.mStatus == STATUS_WAITING_TO_RETRY || mInfoDelta.mStatus == STATUS_WAITING_FOR_NETWORK || mInfoDelta.mStatus == STATUS_QUEUED_FOR_WIFI) {
        Helpers.scheduleJob(mContext, DownloadInfo.queryDownloadInfo(mContext, mId));
    }
    mJobService.jobFinishedInternal(mParams, false);
}
Example 91
Project: XobotOS-master  File: GsmDataConnectionTracker.java View source code
public void run() {
    long sent, received;
    long preTxPkts = -1, preRxPkts = -1;
    Activity newActivity;
    preTxPkts = mTxPkts;
    preRxPkts = mRxPkts;
    long txSum = 0, rxSum = 0;
    for (ApnContext apnContext : mApnContexts.values()) {
        if (apnContext.getState() == State.CONNECTED) {
            DataConnectionAc dcac = apnContext.getDataConnectionAc();
            if (dcac == null)
                continue;
            LinkProperties linkProp = dcac.getLinkPropertiesSync();
            if (linkProp == null)
                continue;
            String iface = linkProp.getInterfaceName();
            if (iface != null) {
                long stats = TrafficStats.getTxPackets(iface);
                if (stats > 0)
                    txSum += stats;
                stats = TrafficStats.getRxPackets(iface);
                if (stats > 0)
                    rxSum += stats;
            }
        }
    }
    mTxPkts = txSum;
    mRxPkts = rxSum;
    if (mNetStatPollEnabled && (preTxPkts > 0 || preRxPkts > 0)) {
        sent = mTxPkts - preTxPkts;
        received = mRxPkts - preRxPkts;
        if (sent > 0 && received > 0) {
            mSentSinceLastRecv = 0;
            newActivity = Activity.DATAINANDOUT;
            mPdpResetCount = 0;
            mRecoveryAction = RecoveryAction.REREGISTER;
        } else if (sent > 0 && received == 0) {
            if (mPhone.getState() == Phone.State.IDLE) {
                mSentSinceLastRecv += sent;
            } else {
                mSentSinceLastRecv = 0;
            }
            newActivity = Activity.DATAOUT;
        } else if (sent == 0 && received > 0) {
            mSentSinceLastRecv = 0;
            newActivity = Activity.DATAIN;
            mPdpResetCount = 0;
            mRecoveryAction = RecoveryAction.REREGISTER;
        } else if (sent == 0 && received == 0) {
            newActivity = Activity.NONE;
        } else {
            mSentSinceLastRecv = 0;
            newActivity = Activity.NONE;
        }
        if (mActivity != newActivity && mIsScreenOn) {
            mActivity = newActivity;
            mPhone.notifyDataActivity();
        }
    }
    int watchdogTrigger = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT, NUMBER_SENT_PACKETS_OF_HANG);
    if (mSentSinceLastRecv >= watchdogTrigger) {
        // we already have NUMBER_SENT_PACKETS sent without ack
        if (mNoRecvPollCount == 0) {
            EventLog.writeEvent(EventLogTags.PDP_RADIO_RESET_COUNTDOWN_TRIGGERED, mSentSinceLastRecv);
        }
        int noRecvPollLimit = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT, NO_RECV_POLL_LIMIT);
        if (mNoRecvPollCount < noRecvPollLimit) {
            // Start polling the context list in an attempt to recover.
            if (DBG)
                log("Polling: no DATAIN in a while; polling PDP");
            mPhone.mCM.getDataCallList(obtainMessage(EVENT_DATA_STATE_CHANGED));
            mNoRecvPollCount++;
            // Slow down the poll interval to let things happen
            mNetStatPollPeriod = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_ERROR_POLL_INTERVAL_MS, POLL_NETSTAT_SLOW_MILLIS);
        } else {
            if (DBG)
                log("Polling: Sent " + String.valueOf(mSentSinceLastRecv) + " pkts since last received start recovery process");
            mNoRecvPollCount = 0;
            sendMessage(obtainMessage(EVENT_START_RECOVERY));
        }
    } else {
        mNoRecvPollCount = 0;
        if (mIsScreenOn) {
            mNetStatPollPeriod = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS);
        } else {
            mNetStatPollPeriod = Settings.Secure.getInt(mResolver, Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS, POLL_NETSTAT_SCREEN_OFF_MILLIS);
        }
    }
    if (mNetStatPollEnabled) {
        mDataConnectionTracker.postDelayed(this, mNetStatPollPeriod);
    }
}
Example 92
Project: andriod_device_coolpad_d530-master  File: CdmaDataConnectionTracker.java View source code
public void run() {
    long sent, received;
    long preTxPkts = -1, preRxPkts = -1;
    Activity newActivity;
    preTxPkts = txPkts;
    preRxPkts = rxPkts;
    txPkts = TrafficStats.getMobileTxPackets();
    rxPkts = TrafficStats.getMobileRxPackets();
    if (netStatPollEnabled && (preTxPkts > 0 || preRxPkts > 0)) {
        sent = txPkts - preTxPkts;
        received = rxPkts - preRxPkts;
        if (sent > 0 && received > 0) {
            sentSinceLastRecv = 0;
            newActivity = Activity.DATAINANDOUT;
        } else if (sent > 0 && received == 0) {
            if (phone.getState() == Phone.State.IDLE) {
                sentSinceLastRecv += sent;
            } else {
                sentSinceLastRecv = 0;
            }
            newActivity = Activity.DATAOUT;
        } else if (sent == 0 && received > 0) {
            sentSinceLastRecv = 0;
            newActivity = Activity.DATAIN;
        } else if (sent == 0 && received == 0) {
            newActivity = (activity == Activity.DORMANT) ? activity : Activity.NONE;
        } else {
            sentSinceLastRecv = 0;
            newActivity = (activity == Activity.DORMANT) ? activity : Activity.NONE;
        }
        if (activity != newActivity) {
            activity = newActivity;
            phone.notifyDataActivity();
        }
    }
    if (sentSinceLastRecv >= NUMBER_SENT_PACKETS_OF_HANG) {
        if (mNoRecvPollCount == 0) {
            EventLog.writeEvent(EventLogTags.PDP_RADIO_RESET_COUNTDOWN_TRIGGERED, sentSinceLastRecv);
        }
        if (mNoRecvPollCount < NO_RECV_POLL_LIMIT) {
            mNoRecvPollCount++;
            // Slow down the poll interval to let things happen
            netStatPollPeriod = POLL_NETSTAT_SLOW_MILLIS;
        } else {
            if (DBG)
                log("Sent " + String.valueOf(sentSinceLastRecv) + " pkts since last received");
            // We've exceeded the threshold.  Restart the radio.
            netStatPollEnabled = false;
            stopNetStatPoll();
            restartRadio();
            EventLog.writeEvent(EventLogTags.PDP_RADIO_RESET, NO_RECV_POLL_LIMIT);
        }
    } else {
        mNoRecvPollCount = 0;
        netStatPollPeriod = POLL_NETSTAT_MILLIS;
    }
    if (netStatPollEnabled) {
        mDataConnectionTracker.postDelayed(this, netStatPollPeriod);
    }
}
Example 93
Project: ijoyplus-android-master  File: VideoPlayerActivity.java View source code
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    // android.util.Log.i("player_yy", "onCreate");
    if (!LibsChecker.checkVitamioLibs(this, R.string.init_decoders))
        return;
    setContentView(R.layout.videoview);
    // ��常亮
    findViewById(R.id.layout).setKeepScreenOn(true);
    mContext = this;
    app = (App) getApplication();
    aq = new AQuery(this);
    // ���次进�当�没有任何集数记录
    Constant.select_index = -1;
    cacheManager = new VideoCacheManager(VideoPlayerActivity.this);
    cacheInfo = new VideoCacheInfo();
    playrecordmanager = new PlayRecordManager(VideoPlayerActivity.this);
    playrecordinfo = new PlayRecordInfo();
    user_id = app.UserID;
    macAddress = app.GetServiceData("Binding_TV_Channal");
    tv_channel = "/screencast/" + macAddress;
    if (macAddress != null) {
        FayeService.FayeByService(mContext, tv_channel);
        registerBinding();
    }
    InitPlayData();
    // �次播放时�时把播放的flag清除为0
    if (app.use2G3G) {
        app.use2G3G = false;
    }
    mVideoView = (VideoView) findViewById(R.id.surface_view);
    mVolumeBrightnessLayout = findViewById(R.id.operation_volume_brightness);
    mOperationBg = (ImageView) findViewById(R.id.operation_bg);
    mOperationPercent = (ImageView) findViewById(R.id.operation_percent);
    mImage_preload_bg = (ImageView) findViewById(R.id.layout_preload_bg);
    mRelativeLayoutBG = findViewById(R.id.relativeLayout_preload);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    mImage_preload_bg.setBackgroundResource(R.drawable.player_bg);
    mRelativeLayoutBG.setVisibility(View.VISIBLE);
    mVideoView.setLayoutBG(mRelativeLayoutBG);
    app = (App) getApplication();
    aq = new AQuery(this);
    mStartRX = TrafficStats.getTotalRxBytes();
    mStartTX = TrafficStats.getTotalTxBytes();
    if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
        aq.id(R.id.textViewRate).text("Your device does not support traffic stat monitoring.");
    } else {
        // test,yy
        mHandler.postDelayed(// test,yy
        mRunnable, // test,yy
        1000);
    }
    mMediaController = new MediaController(this, user_id, tv_channel);
    if (mTitle != null && mTitle.length() > 0) {
        aq.id(R.id.textView1).text("正在载入 ...");
        if (playProdSubName != null && playProdSubName.length() > 0) {
            aq.id(R.id.mediacontroller_file_name).text(mTitle + playProdSubName);
            mVideoView.setTitle(mTitle + playProdSubName);
            mMediaController.setFileName(mTitle + playProdSubName);
            mMediaController.setSubName(playProdSubName);
        } else {
            aq.id(R.id.mediacontroller_file_name).text(mTitle);
            mVideoView.setTitle(mTitle);
            mMediaController.setFileName(mTitle);
        }
    }
    mVideoView.setApp(app);
    mMediaController.setApp(app);
    mVideoView.setOnCompletionListener(this);
    // 设置显示å??ç§°
    if (play_current_time > 0) {
        aq.id(R.id.textView2).text("上次播放到 " + stringForTime(play_current_time));
        mVideoView.JumpTo(play_current_time);
    } else {
        aq.id(R.id.textView2).invisible();
    }
    mVideoView.setMediaController(mMediaController);
    mVideoView.requestFocus();
    mGestureDetector = new GestureDetector(this, new MyGestureListener());
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    if (android.os.Build.VERSION.SDK_INT >= 14) {
        Intent i = new Intent();
        i.setClass(this, DlnaSelectDevice.class);
        bindService(i, mServiceConnection, BIND_AUTO_CREATE);
    }
    checkBind = true;
    if (!URLUtil.isNetworkUrl(mPath)) {
        aq.id(R.id.textViewRate).gone();
        mVideoView.setVideoPath(mPath);
    } else {
        mCurrentPlayData = app.getCurrentPlayData();
        if (playProdId != null)
            GetServiceData();
    }
    mvediohandler = new Handler() {

        public void handleMessage(Message msg) {
            // android.util.Log.i("player_yy",msg.what+"");
            switch(msg.what) {
                case VideoPlay:
                    if (msg.obj.toString().contains("{now_date}")) {
                        long time = System.currentTimeMillis() / 1000;
                        String msgUrl = msg.obj.toString().replace("{now_date}", time + "");
                        videoplay(msgUrl);
                    } else {
                        videoplay(msg.obj.toString());
                    }
                    break;
                default:
                    android.util.Log.i("player_yy", "error");
            }
        }
    };
}
Example 94
Project: cnAndroidDocs-master  File: WifiService.java View source code
private void notifyOnDataActivity() {
    long sent, received;
    long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
    int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
    mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
    mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
    if (preTxPkts > 0 || preRxPkts > 0) {
        sent = mTxPkts - preTxPkts;
        received = mRxPkts - preRxPkts;
        if (sent > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
        }
        if (received > 0) {
            dataActivity |= WifiManager.DATA_ACTIVITY_IN;
        }
        if (dataActivity != mDataActivity && !mScreenOff) {
            mDataActivity = dataActivity;
            for (AsyncChannel client : mClients) {
                client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
            }
        }
    }
}
Example 95
Project: DragonGoApp-master  File: GoJsActivity.java View source code
void initGUI() {
    // ====================================
    setContentView(R.layout.activity_main);
    wv = (WebView) findViewById(R.id.web1);
    wv.setWebViewClient(new myWebViewClient());
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setSupportZoom(true);
    //		String myHTML  = "<html><body><a href='androidcall01|123456'>Call Back to Android 01 with param 123456</a>my Content<p>my Content<p>my Content<p><a href='androidcall02|7890123'>Call Back to Android 01 with param 7890123</a></body></html>";
    //		wv.loadDataWithBaseURL("about:blank", myHTML, "text/html", "utf-8", "");
    //		wv.addJavascriptInterface(new WebAppInterface(this), "Android");
    {
        final Button button = (Button) findViewById(R.id.morebutts);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("press last button on state " + curstate);
                showMoreButtons();
            }
        });
    }
    {
        final Button button = (Button) findViewById(R.id.but1);
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                System.out.println("press button1 on state " + curstate);
                switch(curstate) {
                    // download games
                    case nogame:
                        downloadListOfGames();
                        break;
                    // send the move
                    case play:
                        // ask eidogo to send last move; it will be captured by the web listener
                        System.out.println("DEBUG SENDING MOVE TO SERVER");
                        wv.loadUrl("javascript:eidogo.autoPlayers[0].detsonSend()");
                        break;
                    case // send a request to the server to compute the score
                    markDeadStones:
                        // wv.loadUrl("javascript:eidogo.autoPlayers[0].detsonSend()");
                        break;
                    // accept the current score evaluation
                    case checkScore:
                        acceptScore();
                        break;
                    // get messages
                    case message:
                        if (!initServer())
                            return;
                        Message.downloadMessages(server, main);
                        break;
                    case // reprint comment
                    review:
                        longToast(Reviews.comment, 5);
                        break;
                }
            //	              {
            //	                  Intent intent = new Intent(Intent.ACTION_VIEW);
            //	                  intent.addCategory(Intent.CATEGORY_BROWSABLE);
            //	                  intent.setDataAndType(Uri.fromFile(ff), "application/x-webarchive-xml");
            //	                  //                  intent.setDataAndType(Uri.fromFile(ff), "text/html");
            //	                  intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
            //	                  //                  intent.setClassName("Lnu.tommie.inbrowser", "com.android.browser.BrowserActivity");
            //	                  startActivity(intent);
            //	                  // to launch a browser:
            //	                  //                  Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("file:///mnt/sdcard/"));
            //	              }
            }
        });
    }
    {
        final Button button = (Button) findViewById(R.id.but2);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("press button2 on state " + curstate);
                switch(curstate) {
                    case nogame:
                    case play:
                    case markDeadStones:
                    case checkScore:
                    case review:
                        wv.zoomIn();
                        wv.invalidate();
                        break;
                    // send invitation
                    case message:
                        System.out.println("send invitation");
                        if (!initServer())
                            return;
                        Message.invite(server, main);
                        break;
                }
            }
        });
    }
    {
        final Button button = (Button) findViewById(R.id.but3);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("press button3 on state " + curstate);
                switch(curstate) {
                    case nogame:
                    case play:
                    case markDeadStones:
                    case review:
                    case checkScore:
                        wv.zoomOut();
                        wv.invalidate();
                        break;
                    // send message
                    case message:
                        if (!initServer()) {
                            showMessage("Connection problem");
                        } else
                            Message.send(server, main);
                        break;
                }
            }
        });
    }
    {
        final Button button = (Button) findViewById(R.id.but4);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("press button4 on state " + curstate);
                switch(curstate) {
                    case // send message
                    nogame:
                        changeState(guistate.message);
                        break;
                    case // reset to the original download SGF
                    play:
                        showGame(Game.gameShown);
                        break;
                    case // cancels marking stones and comes back to playing
                    markDeadStones:
                        changeState(guistate.play);
                        break;
                    case // refuse score and continues to mark stones
                    checkScore:
                        refuseScore();
                        break;
                    case // go back to last game mode
                    message:
                        changeState(lastGameState);
                        break;
                    case review:
                        Reviews.showList();
                        break;
                }
            }
        });
    }
    {
        final Button button = (Button) findViewById(R.id.but5);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("press button5 on state " + curstate);
                CharSequence t = button.getText();
                if (t.equals("Fwd"))
                    wv.loadUrl("javascript:eidogo.autoPlayers[0].fwd()");
                else if (t.equals("Bck"))
                    wv.loadUrl("javascript:eidogo.autoPlayers[0].backward()");
                else
                    Log.w("button5", "unknow text " + t);
            }
        });
    }
    // ====================================
    // copy the eidogo dir into the external sdcard
    // only copy if it does not exist already
    // this takes time, so do it in a thread and show a message for the user to wait
    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }
    if (mExternalStorageAvailable && mExternalStorageWriteable) {
        File d = getExternalCacheDir();
        eidogodir = new File(d, "eidogo");
        if (forcecopy || !eidogodir.exists()) {
            eidogodir.mkdirs();
            final Button button3 = (Button) findViewById(R.id.but3);
            button3.setClickable(false);
            button3.setEnabled(false);
            final Button button2 = (Button) findViewById(R.id.but2);
            button2.setClickable(false);
            button2.setEnabled(false);
            final Button button1 = (Button) findViewById(R.id.but1);
            button1.setClickable(false);
            button1.setEnabled(false);
            button1.invalidate();
            button2.invalidate();
            button3.invalidate();
            new CopyEidogoTask().execute("noparms");
        } else {
            showMessage("eidogo already on disk");
            initFinished();
        }
    } else {
        showMessage("R/W ERROR sdcard");
    }
    // manage events to show/hide the waiting dialog
    main = this;
    final EventManager em = EventManager.getEventManager();
    EventManager.EventListener waitDialogShower = new EventManager.EventListener() {

        @Override
        public String getName() {
            return "onStartShowWaitDialog";
        }

        @Override
        public synchronized void reactToEvent() {
            GUI.showWaitingWin();
            numEventsReceived++;
        }
    };
    // we put here all events that should trigger the "waiting" dialog
    em.registerListener(eventType.downloadGameStarted, waitDialogShower);
    em.registerListener(eventType.downloadListStarted, waitDialogShower);
    em.registerListener(eventType.loginStarted, waitDialogShower);
    em.registerListener(eventType.moveSentStart, waitDialogShower);
    em.registerListener(eventType.ladderStart, waitDialogShower);
    em.registerListener(eventType.ladderChallengeStart, waitDialogShower);
    em.registerListener(eventType.copyEidogoStart, waitDialogShower);
    EventManager.EventListener waitDialogHider = new EventManager.EventListener() {

        @Override
        public String getName() {
            return "onStartHideWaitDialog";
        }

        @Override
        public synchronized void reactToEvent() {
            try {
                --numEventsReceived;
                if (numEventsReceived < 0) {
                    System.out.println("ERROR events stream...");
                    return;
                }
                if (numEventsReceived == 0) {
                    GUI.hideWaitingWin();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    em.registerListener(eventType.downloadGameEnd, waitDialogHider);
    em.registerListener(eventType.downloadListEnd, waitDialogHider);
    em.registerListener(eventType.loginEnd, waitDialogHider);
    em.registerListener(eventType.moveSentEnd, waitDialogHider);
    em.registerListener(eventType.ladderEnd, waitDialogHider);
    em.registerListener(eventType.ladderChallengeEnd, waitDialogHider);
    em.registerListener(eventType.copyEidogoEnd, waitDialogHider);
    // to show message
    em.registerListener(eventType.showMessage, new EventManager.EventListener() {

        @Override
        public void reactToEvent() {
            showMessage(EventManager.getEventManager().message);
        }

        @Override
        public String getName() {
            return "showMessage";
        }
    });
    // initialize guistate
    changeState(guistate.nogame);
    //        {
    //            // initialize pushserver
    //            int valInConfig = PrefUtils.getFromPrefs(getApplicationContext(),PrefUtils.PREFS_PUSHSERVER,1);
    //            WSclient.setConnect(valInConfig==1?true:false);
    //        }
    {
        // initialize active Go servers
        int valInConfig = PrefUtils.getFromPrefs(getApplicationContext(), PrefUtils.PREFS_DGSON, 1);
        getGamesFromDGS = (valInConfig == 1 ? true : false);
        valInConfig = PrefUtils.getFromPrefs(getApplicationContext(), PrefUtils.PREFS_OGSON, 1);
        getGamesFromOGS = (valInConfig == 1 ? true : false);
    }
    // initialize traffic stats
    ActivityManager mgr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    // strange: the initial bandwidth of this uid is not 0 ?!
    uid = Process.myUid();
    rx = TrafficStats.getTotalRxBytes();
    tx = TrafficStats.getTotalTxBytes();
    if (rx0 == -7) {
        rx0 = rx;
        tx0 = tx;
    }
    if (rx == TrafficStats.UNSUPPORTED || tx == TrafficStats.UNSUPPORTED) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Uh Oh!");
        alert.setMessage("Your device does not support traffic stat monitoring.");
        alert.show();
    } else {
        mHandler.postDelayed(mRunnable, 3000);
    }
    writeTraffix(rx + tx);
}
Example 96
Project: MobiPerf-master  File: RRCTask.java View source code
/**
     * Determine how many packets, so far, have been sent (the contents of /proc/net/dev/). This is
     * a global value. We use this to determine if any other app anywhere on the phone may have sent
     * interfering traffic that might have changed the RRC state without our knowledge.
     * 
     * @return Two values: number of bytes or packets received at index 0, followed by the number 
     * sent at index 1.  
     */
public long[] getPacketsSent() {
    long[] retval = { -1, -1 };
    if (bySize) {
        retval[0] = TrafficStats.getMobileRxBytes();
        retval[1] = TrafficStats.getMobileTxBytes();
    } else {
        retval[0] = TrafficStats.getMobileRxPackets();
        retval[1] = TrafficStats.getMobileTxPackets();
    }
    return retval;
}
Example 97
Project: AndroidMail-master  File: MessagingController.java View source code
// TODO For now, mailbox addition occurs in the server-dependent store implementation,
// but, mailbox removal occurs here. Instead, each store should be responsible for
// content synchronization (addition AND removal) since each store will likely need
// to implement it's own, unique synchronization methodology.
public void run() {
    TrafficStats.setThreadStatsTag(TrafficFlags.getSyncFlags(mContext, account));
    Cursor localFolderCursor = null;
    try {
        // Step 1: Get remote mailboxes
        Store store = Store.getInstance(account, mContext);
        Folder[] remoteFolders = store.updateFolders();
        HashSet<String> remoteFolderNames = new HashSet<String>();
        for (int i = 0, count = remoteFolders.length; i < count; i++) {
            remoteFolderNames.add(remoteFolders[i].getName());
        }
        // Step 2: Get local mailboxes
        localFolderCursor = mContext.getContentResolver().query(Mailbox.CONTENT_URI, MAILBOX_PROJECTION, EmailContent.MailboxColumns.ACCOUNT_KEY + "=?", new String[] { String.valueOf(account.mId) }, null);
        // Step 3: Remove any local mailbox not on the remote list
        while (localFolderCursor.moveToNext()) {
            String mailboxPath = localFolderCursor.getString(MAILBOX_COLUMN_SERVER_ID);
            // Short circuit if we have a remote mailbox with the same name
            if (remoteFolderNames.contains(mailboxPath)) {
                continue;
            }
            int mailboxType = localFolderCursor.getInt(MAILBOX_COLUMN_TYPE);
            long mailboxId = localFolderCursor.getLong(MAILBOX_COLUMN_ID);
            switch(mailboxType) {
                case Mailbox.TYPE_INBOX:
                case Mailbox.TYPE_DRAFTS:
                case Mailbox.TYPE_OUTBOX:
                case Mailbox.TYPE_SENT:
                case Mailbox.TYPE_TRASH:
                case Mailbox.TYPE_SEARCH:
                    // Never, ever delete special mailboxes
                    break;
                default:
                    // Drop all attachment files related to this mailbox
                    AttachmentUtilities.deleteAllMailboxAttachmentFiles(mContext, accountId, mailboxId);
                    // Delete the mailbox; database triggers take care of related
                    // Message, Body and Attachment records
                    Uri uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId);
                    mContext.getContentResolver().delete(uri, null, null);
                    break;
            }
        }
        mListeners.listFoldersFinished(accountId);
    } catch (Exception e) {
        mListeners.listFoldersFailed(accountId, e.toString());
    } finally {
        if (localFolderCursor != null) {
            localFolderCursor.close();
        }
    }
}
Example 98
Project: CompilingAndroidMail-master  File: MessagingController.java View source code
// TODO For now, mailbox addition occurs in the server-dependent store implementation,
// but, mailbox removal occurs here. Instead, each store should be responsible for
// content synchronization (addition AND removal) since each store will likely need
// to implement it's own, unique synchronization methodology.
public void run() {
    TrafficStats.setThreadStatsTag(TrafficFlags.getSyncFlags(mContext, account));
    Cursor localFolderCursor = null;
    try {
        // Step 1: Get remote mailboxes
        Store store = Store.getInstance(account, mContext);
        Folder[] remoteFolders = store.updateFolders();
        HashSet<String> remoteFolderNames = new HashSet<String>();
        for (int i = 0, count = remoteFolders.length; i < count; i++) {
            remoteFolderNames.add(remoteFolders[i].getName());
        }
        // Step 2: Get local mailboxes
        localFolderCursor = mContext.getContentResolver().query(Mailbox.CONTENT_URI, MAILBOX_PROJECTION, EmailContent.MailboxColumns.ACCOUNT_KEY + "=?", new String[] { String.valueOf(account.mId) }, null);
        // Step 3: Remove any local mailbox not on the remote list
        while (localFolderCursor.moveToNext()) {
            String mailboxPath = localFolderCursor.getString(MAILBOX_COLUMN_SERVER_ID);
            // Short circuit if we have a remote mailbox with the same name
            if (remoteFolderNames.contains(mailboxPath)) {
                continue;
            }
            int mailboxType = localFolderCursor.getInt(MAILBOX_COLUMN_TYPE);
            long mailboxId = localFolderCursor.getLong(MAILBOX_COLUMN_ID);
            switch(mailboxType) {
                case Mailbox.TYPE_INBOX:
                case Mailbox.TYPE_DRAFTS:
                case Mailbox.TYPE_OUTBOX:
                case Mailbox.TYPE_SENT:
                case Mailbox.TYPE_TRASH:
                case Mailbox.TYPE_SEARCH:
                    // Never, ever delete special mailboxes
                    break;
                default:
                    // Drop all attachment files related to this mailbox
                    AttachmentUtilities.deleteAllMailboxAttachmentFiles(mContext, accountId, mailboxId);
                    // Delete the mailbox; database triggers take care of related
                    // Message, Body and Attachment records
                    Uri uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId);
                    mContext.getContentResolver().delete(uri, null, null);
                    break;
            }
        }
        mListeners.listFoldersFinished(accountId);
    } catch (Exception e) {
        mListeners.listFoldersFailed(accountId, e.toString());
    } finally {
        if (localFolderCursor != null) {
            localFolderCursor.close();
        }
    }
}
Example 99
Project: NetGuard-master  File: ServiceSinkhole.java View source code
private void updateStats() {
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.traffic);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSinkhole.this);
    long frequency = Long.parseLong(prefs.getString("stats_frequency", "1000"));
    long samples = Long.parseLong(prefs.getString("stats_samples", "90"));
    boolean filter = prefs.getBoolean("filter", false);
    boolean show_top = prefs.getBoolean("show_top", false);
    int loglevel = Integer.parseInt(prefs.getString("loglevel", Integer.toString(Log.WARN)));
    // Schedule next update
    this.sendEmptyMessageDelayed(MSG_STATS_UPDATE, frequency);
    long ct = SystemClock.elapsedRealtime();
    // Cleanup
    while (gt.size() > 0 && ct - gt.get(0) > samples * 1000) {
        gt.remove(0);
        gtx.remove(0);
        grx.remove(0);
    }
    // Calculate network speed
    float txsec = 0;
    float rxsec = 0;
    long ttx = TrafficStats.getTotalTxBytes();
    long trx = TrafficStats.getTotalRxBytes();
    if (filter) {
        ttx -= TrafficStats.getUidTxBytes(Process.myUid());
        trx -= TrafficStats.getUidRxBytes(Process.myUid());
        if (ttx < 0)
            ttx = 0;
        if (trx < 0)
            trx = 0;
    }
    if (t > 0 && tx > 0 && rx > 0) {
        float dt = (ct - t) / 1000f;
        txsec = (ttx - tx) / dt;
        rxsec = (trx - rx) / dt;
        gt.add(ct);
        gtx.add(txsec);
        grx.add(rxsec);
    }
    // Calculate application speeds
    if (show_top) {
        if (mapUidBytes.size() == 0) {
            for (ApplicationInfo ainfo : getPackageManager().getInstalledApplications(0)) if (ainfo.uid != Process.myUid())
                mapUidBytes.put(ainfo.uid, TrafficStats.getUidTxBytes(ainfo.uid) + TrafficStats.getUidRxBytes(ainfo.uid));
        } else if (t > 0) {
            TreeMap<Float, Integer> mapSpeedUid = new TreeMap<>(new Comparator<Float>() {

                @Override
                public int compare(Float value, Float other) {
                    return -value.compareTo(other);
                }
            });
            float dt = (ct - t) / 1000f;
            for (int uid : mapUidBytes.keySet()) {
                long bytes = TrafficStats.getUidTxBytes(uid) + TrafficStats.getUidRxBytes(uid);
                float speed = (bytes - mapUidBytes.get(uid)) / dt;
                if (speed > 0) {
                    mapSpeedUid.put(speed, uid);
                    mapUidBytes.put(uid, bytes);
                }
            }
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for (float speed : mapSpeedUid.keySet()) {
                if (i++ >= 3)
                    break;
                if (speed < 1000 * 1000)
                    sb.append(getString(R.string.msg_kbsec, speed / 1000));
                else
                    sb.append(getString(R.string.msg_mbsec, speed / 1000 / 1000));
                sb.append(' ');
                List<String> apps = Util.getApplicationNames(mapSpeedUid.get(speed), ServiceSinkhole.this);
                sb.append(apps.size() > 0 ? apps.get(0) : "?");
                sb.append("\r\n");
            }
            if (sb.length() > 0)
                sb.setLength(sb.length() - 2);
            remoteViews.setTextViewText(R.id.tvTop, sb.toString());
        }
    }
    t = ct;
    tx = ttx;
    rx = trx;
    // Create bitmap
    int height = Util.dips2pixels(96, ServiceSinkhole.this);
    int width = Util.dips2pixels(96 * 5, ServiceSinkhole.this);
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    // Create canvas
    Canvas canvas = new Canvas(bitmap);
    canvas.drawColor(Color.TRANSPARENT);
    // Determine max
    float max = 0;
    long xmax = 0;
    float ymax = 0;
    for (int i = 0; i < gt.size(); i++) {
        long t = gt.get(i);
        float tx = gtx.get(i);
        float rx = grx.get(i);
        if (t > xmax)
            xmax = t;
        if (tx > max)
            max = tx;
        if (rx > max)
            max = rx;
        if (tx > ymax)
            ymax = tx;
        if (rx > ymax)
            ymax = rx;
    }
    // Build paths
    Path ptx = new Path();
    Path prx = new Path();
    for (int i = 0; i < gtx.size(); i++) {
        float x = width - width * (xmax - gt.get(i)) / 1000f / samples;
        float ytx = height - height * gtx.get(i) / ymax;
        float yrx = height - height * grx.get(i) / ymax;
        if (i == 0) {
            ptx.moveTo(x, ytx);
            prx.moveTo(x, yrx);
        } else {
            ptx.lineTo(x, ytx);
            prx.lineTo(x, yrx);
        }
    }
    // Build paint
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setStyle(Paint.Style.STROKE);
    // Draw scale line
    paint.setStrokeWidth(Util.dips2pixels(1, ServiceSinkhole.this));
    paint.setColor(ContextCompat.getColor(ServiceSinkhole.this, R.color.colorGrayed));
    float y = height / 2;
    canvas.drawLine(0, y, width, y, paint);
    // Draw paths
    paint.setStrokeWidth(Util.dips2pixels(2, ServiceSinkhole.this));
    paint.setColor(ContextCompat.getColor(ServiceSinkhole.this, R.color.colorSend));
    canvas.drawPath(ptx, paint);
    paint.setColor(ContextCompat.getColor(ServiceSinkhole.this, R.color.colorReceive));
    canvas.drawPath(prx, paint);
    // Update remote view
    remoteViews.setImageViewBitmap(R.id.ivTraffic, bitmap);
    if (txsec < 1000 * 1000)
        remoteViews.setTextViewText(R.id.tvTx, getString(R.string.msg_kbsec, txsec / 1000));
    else
        remoteViews.setTextViewText(R.id.tvTx, getString(R.string.msg_mbsec, txsec / 1000 / 1000));
    if (rxsec < 1000 * 1000)
        remoteViews.setTextViewText(R.id.tvRx, getString(R.string.msg_kbsec, rxsec / 1000));
    else
        remoteViews.setTextViewText(R.id.tvRx, getString(R.string.msg_mbsec, rxsec / 1000 / 1000));
    if (max < 1000 * 1000)
        remoteViews.setTextViewText(R.id.tvMax, getString(R.string.msg_kbsec, max / 2 / 1000));
    else
        remoteViews.setTextViewText(R.id.tvMax, getString(R.string.msg_mbsec, max / 2 / 1000 / 1000));
    // Show session/file count
    if (filter && loglevel <= Log.WARN) {
        int[] count = jni_get_stats();
        remoteViews.setTextViewText(R.id.tvSessions, count[0] + "/" + count[1] + "/" + count[2]);
        remoteViews.setTextViewText(R.id.tvFiles, count[3] + "/" + count[4]);
    } else {
        remoteViews.setTextViewText(R.id.tvSessions, "");
        remoteViews.setTextViewText(R.id.tvFiles, "");
    }
    // Show notification
    Intent main = new Intent(ServiceSinkhole.this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(ServiceSinkhole.this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(ServiceSinkhole.this).setWhen(when).setSmallIcon(R.drawable.ic_equalizer_white_24dp).setContent(remoteViews).setContentIntent(pi).setColor(tv.data).setOngoing(true).setAutoCancel(false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_PUBLIC);
    }
    if (state == State.none || state == State.waiting) {
        if (state != State.none) {
            Log.d(TAG, "Stop foreground state=" + state.toString());
            stopForeground(true);
        }
        startForeground(NOTIFY_TRAFFIC, builder.build());
        state = State.stats;
        Log.d(TAG, "Start foreground state=" + state.toString());
    } else
        NotificationManagerCompat.from(ServiceSinkhole.this).notify(NOTIFY_TRAFFIC, builder.build());
}
Example 100
Project: MiBandDecompiled-master  File: o.java View source code
public static void a() {
    TrafficStats.clearThreadStatsTag();
}
Example 101
Project: neembuunow-master  File: TrafficStatsCompatIcs.java View source code
public static int getThreadStatsTag() {
    return TrafficStats.getThreadStatsTag();
}