Example usage for java.util Timer scheduleAtFixedRate

List of usage examples for java.util Timer scheduleAtFixedRate

Introduction

In this page you can find the example usage for java.util Timer scheduleAtFixedRate.

Prototype

public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 

Source Link

Document

Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

Usage

From source file:org.brandroid.openmanager.fragments.DialogHandler.java

/**
 * Show a warning that has a specific count down to auto-cancel.
 * @param context Context./*from  w  w w  .j ava2  s.  c om*/
 * @param msg Message String ID.
 * @param countSecs Length in seconds to show message before auto-cancelling.
 * @param onOK Callback for when "OK" is selected.
 * @return
 */
public static AlertDialog showWarning(final Context context, int msg, int countSecs,
        DialogInterface.OnClickListener onOK) {
    final Timer timer = new Timer("Count Down");
    final AlertDialog dlg = new AlertDialog.Builder(context).setMessage(msg)
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    timer.cancel();
                }
            }).setCancelable(true).setPositiveButton(android.R.string.ok, onOK).show();
    final int[] cnt = new int[] { countSecs };
    final Button btCancel = dlg.getButton(DialogInterface.BUTTON_NEGATIVE);
    TimerTask tt = new TimerTask() {
        @Override
        public void run() {
            if (dlg.isShowing()) {
                btCancel.post(new Runnable() {
                    public void run() {
                        btCancel.setText(context.getResources().getString(android.R.string.cancel) + " ("
                                + cnt[0]-- + ")");
                    }
                });
            } else
                cnt[0] = 0;
            if (cnt[0] <= 0)
                cancel();
        }

        @Override
        public boolean cancel() {
            dlg.cancel();
            return super.cancel();
        }
    };
    timer.scheduleAtFixedRate(tt, 0, 1000);
    return dlg;
}

From source file:net.bashtech.geobot.BotManager.java

public BotManager(String propertiesFile) {
    BotManager.setInstance(this);
    _propertiesFile = propertiesFile;// ww  w. j ava 2 s . co  m
    channelList = new HashMap<String, Channel>();
    blockedChannelList = new HashSet<String>();
    admins = new HashSet<String>();
    modules = new HashSet<BotModule>();
    tagAdmins = new HashSet<String>();
    tagStaff = new HashSet<String>();
    emoteSet = new LinkedList<String>();
    globalBannedWords = new LinkedList<Pattern>();
    emoteSetMapping = new HashMap<String, Set<String>>();
    banPhraseLists = new HashMap<Integer, List<Pattern>>();

    loadGlobalProfile();

    if (useGUI) {
        gui = new BotGUI();
    }

    receiverBot = new ReceiverBot(server, port);
    List<String> outdatedChannels = new LinkedList<String>();
    for (Map.Entry<String, Channel> entry : channelList.entrySet()) {
        String channel = entry.getValue().getChannel();
        if (!JSONUtil.krakenOutdatedChannel(channel.substring(1))
                || receiverBot.getNick().equalsIgnoreCase(channel.substring(1))
                || entry.getValue().staticChannel) {
            log("BM: Joining channel " + channel);
            receiverBot.joinChannel(channel.toLowerCase(), true);
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            outdatedChannels.add(channel);
        }

    }
    receiverBot.startPusher();
    receiverBot.startJoinCheck();
    log("BM: Done Joining Channels");

    // Start EventFeedReader
    if (useEventFeed) {
        Runnable task = new EventFeedReader();
        Thread worker = new Thread(task);
        worker.setName("Reader");
        worker.start();
    }

    // Remove outdatedChannels
    for (String channel : outdatedChannels) {
        log("BM: Removing channel: " + channel);
        this.removeChannel(channel);
    }

    // Start timer to check for bot disconnects
    Timer reconnectTimer = new Timer();
    reconnectTimer.scheduleAtFixedRate(new ReconnectTimer(channelList), 30 * 1000, 30 * 1000);

}

From source file:org.kontalk.xmppserver.KontalkIqRegister.java

@Override
public void init(Map<String, Object> settings) throws TigaseDBException {
    requests = new HashMap<>();
    throttlingRequests = new HashMap<>();

    // registration providers
    providers = new LinkedHashMap<>();
    String[] providersList = (String[]) settings.get("providers");
    if (providersList == null || providersList.length == 0)
        throw new TigaseDBException("No providers configured");

    String defaultProviderName = (String) settings.get("default-provider");
    String fallbackProviderName = (String) settings.get("fallback-provider");

    for (String providerStr : providersList) {
        String[] providerDef = providerStr.split("=");
        if (providerDef.length != 2)
            throw new TigaseDBException("Bad provider definition: " + providerStr);

        String providerName = providerDef[0];
        String providerClassName = providerDef[1];

        try {/*from w  w  w  . j  a v a2  s  . co  m*/
            @SuppressWarnings("unchecked")
            Class<? extends PhoneNumberVerificationProvider> providerClass = (Class<? extends PhoneNumberVerificationProvider>) Class
                    .forName(providerClassName);
            PhoneNumberVerificationProvider provider = providerClass.newInstance();
            provider.init(getPrefixedSettings(settings, providerName + "-"));
            // init was successful
            providers.put(providerName, provider);

            if (defaultProviderName != null) {
                // this is the default provider
                if (defaultProviderName.equals(providerName))
                    defaultProvider = provider;
            } else if (defaultProvider == null) {
                // no default provider defined, use the first one found
                defaultProvider = provider;
            }

            if (fallbackProviderName != null) {
                // this is the fallback provider
                if (fallbackProviderName.equals(providerName))
                    fallbackProvider = provider;
            } else if (fallbackProvider == null && defaultProvider != null) {
                // no fallback provider defined and default provider already set
                // use the second provider found
                fallbackProvider = provider;
            }
        } catch (ClassNotFoundException e) {
            throw new TigaseDBException("Provider class not found: " + providerClassName);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new TigaseDBException("Unable to create provider instance for " + providerClassName);
        } catch (ConfigurationException e) {
            throw new TigaseDBException("configuration error", e);
        }
    }

    // user repository for periodical purge of old users
    String uri = (String) settings.get("db-uri");
    userRepository.initRepository(uri, null);

    // delete expired users once a day
    long timeout = TimeUnit.DAYS.toMillis(1);
    Timer taskTimer = new Timer(ID + " tasks", true);
    taskTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                if (log.isLoggable(Level.FINEST)) {
                    log.finest("Purging expired users.");
                }
                // TODO seconds should be in configuration
                List<BareJID> users = userRepository.getExpiredUsers(DEF_EXPIRE_SECONDS);
                for (BareJID user : users) {
                    removeUser(user);
                }
            } catch (TigaseDBException e) {
                log.log(Level.WARNING, "error purging expired users", e);
            }
        }
    }, timeout, timeout);
}

From source file:com.corporatetaxi.TaxiOntheWay_Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_taxiontheway);
    taxiOntheWay_activity_instance = this;
    AppPreferences.setApprequestTaxiScreen(TaxiOntheWay_Activity.this, true);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);// w  ww.  j ava 2s .c om
    // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);

    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    fab_call = (FloatingActionButton) findViewById(R.id.fab_call);
    fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    textheader = (TextView) findViewById(R.id.textheader);
    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    taxiname = (TextView) findViewById(R.id.taxinametext);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    taxinamehead = (TextView) findViewById(R.id.taxinamehead);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");

    textheader.setTypeface(tf);
    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);
    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    taxinamehead.setTypeface(tf);
    taxiname.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);

    ////////current date time//////////////////
    currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    Log.d("currentdatetime", currentDateTimeString);

    /////back arrow ////////////
    //        final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
    //        upArrow.setColorFilter(getResources().getColor(R.color.colorbutton), PorterDuff.Mode.SRC_ATOP);
    //        getSupportActionBar().setHomeAsUpIndicator(upArrow);

    /////////////notification data///////////////
    Intent intent = getIntent();
    String data = intent.getStringExtra("data");
    Log.d("data value", data + "");
    // caceldialog();
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(data);
        AppPreferences.setAcceptdriverId(TaxiOntheWay_Activity.this, jsonObject.getString("driverId"));
        Log.d("driverid---", AppPreferences.getAcceptdriverId(TaxiOntheWay_Activity.this));
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        // driverlatitude = jsonObject.getDouble("latitude");
        // driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        Log.d("driveriamge", driverimage);

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        taxiname.setText(drivertaxiname);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }

        Intent intent1 = new Intent(TaxiOntheWay_Activity.this, DriverService.class);
        intent1.putExtra("driverId", jsonObject.getString("driverId"));
        startService(intent1);

        //            loc2 = new LatLng(driverlatitude, driverlongitude);
        //            MarkerOptions marker2 = new MarkerOptions().position(loc2);
        //            marker2.icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi));
        //            map.addMarker(marker2);
        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiOntheWay_Activity.this)),
                            new Double(AppPreferences.getCurrentlong(TaxiOntheWay_Activity.this)));
                        MarkerOptions marker2 = new MarkerOptions().position(loc2);
                        map.clear();
                        marker2.icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi));
                        map.addMarker(marker2.title(drivername));*/
                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiOntheWay_Activity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiOntheWay_Activity.this)));

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                    }
                });

            }
        }, delay, period);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    /////////////notification dataend///////////////
    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();
        }
    });

    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });
    fab_call.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + drivermobile));
            startActivity(callIntent);
        }
    });

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    if (driverimage.equalsIgnoreCase("")) {
        mdriverimage.setImageResource(R.drawable.ic_action_user);

    } else {
        Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                .resize(200, 200).into(mdriverimage);
    }
}

From source file:com.usertaxi.TaxiArrived_Acitivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_taxiarrived);

    taxiArrived_AcitivityInstance = this;

    AppPreferences.setApprequestTaxiScreen(TaxiArrived_Acitivity.this, false);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);/*from ww w. ja  v a 2s .  c o  m*/
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);

    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    FloatingActionButton fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    FloatingActionButton fab_boarded = (FloatingActionButton) findViewById(R.id.fab_boarded);
    FloatingActionButton fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    txt_header = (TextView) findViewById(R.id.textheader);
    //        btn_sendmesssage = (Button) findViewById(R.id.btn_sendmsg);
    //        btn_cancel = (Button) findViewById(R.id.btn_cancel);
    //        btn_boarder = (Button) findViewById(R.id.btn_boarded);
    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");
    txt_header.setTypeface(tf);
    //        btn_sendmesssage.setTypeface(tf);
    //        btn_cancel.setTypeface(tf);
    //        btn_boarder.setTypeface(tf);
    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);

    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);
    /////////////notification data///////////////
    Intent intent = getIntent();
    String data = intent.getStringExtra("data");
    //        caceldialog();

    Log.d("data value", data + "");
    try {
        JSONObject jsonObject = new JSONObject(data);
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        driverlatitude = jsonObject.getDouble("latitude");
        driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        // marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }
        if (driverimage.equalsIgnoreCase("")) {

            mdriverimage.setImageResource(R.drawable.ic_action_user);

        } else {
            Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                    .resize(200, 200).into(mdriverimage);

        }

        //            loc2 = new LatLng(driverlatitude, driverlongitude);
        //            MarkerOptions marker2 = new MarkerOptions().position(loc2);
        //            marker2.icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi));
        //            map.addMarker(marker2);

        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiArrived_Acitivity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiArrived_Acitivity.this)));
                        //loc2 = new LatLng(driverlatitude,driverlongitude);

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                    }
                });

            }
        }, delay, period);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    ////////////notification dataend///////////////
    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();
        }
    });
    fab_boarded.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent1 = new Intent(TaxiArrived_Acitivity.this, RateExperience_Activity.class);

            intent1.putExtra("driver_name", drivername);
            intent1.putExtra("driver_mobile", drivermobile);
            intent1.putExtra("driver_companyname", drivercompanyname);
            intent1.putExtra("driver_taxinumber", drivertexinumber);
            intent1.putExtra("driver_image", driverimage);
            startActivity(intent1);
            new BoardeTripAsynch().execute();

        }
    });
    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });

}

From source file:org.globus.globus.transfer.ManageTransfersFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    manageTransfersList = getListView();
    manageTransfersList.setOnScrollListener(new EndlessScrollListener(10));

    int delay = 5000; // delay for 5 sec.
    int period = 20000; // repeat every 20 sec.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (!loadingNewTasks) {
                loadingNewTasks = true;//from ww w  .j a  v  a2s.co m
                new TransferAPILoad10MoreNewTasks().execute();
            }
        }
    }, delay, period);

    int intervalForRefresh = 7000;
    Timer refresher = new Timer();
    refresher.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            new TransferAPIRefreshTasks().execute();
        }
    }, intervalForRefresh, intervalForRefresh);
}

From source file:ddf.catalog.resource.download.ReliableResourceDownloader.java

@Override
public void run() {
    long bytesRead = 0;
    ReliableResourceStatus reliableResourceStatus = null;
    int retryAttempts = 0;

    try {//  w  ww.  j  a v  a2 s  .c o m
        reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, countingFbos, fos,
                downloaderConfig.getChunkSize(), lock);
        downloadFuture = null;
        ResourceRetrievalMonitor resourceRetrievalMonitor = null;
        this.downloadState.setDownloadState(DownloadManagerState.DownloadState.IN_PROGRESS);

        while (retryAttempts < downloaderConfig.getMaxRetryAttempts()) {
            if (reliableResourceCallable == null) {
                // This usually occurs on retry attempts to download and the
                // ReliableResourceCallable cannot be successfully created. In this case, a
                // partial cache file may have been created from the previous caching attempt(s)
                // and needs to be deleted from the product cache directory.
                LOGGER.debug("ReliableResourceCallable is null - cannot download resource");
                retryAttempts++;
                LOGGER.debug("Download attempt {}", retryAttempts);
                eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING, metacard,
                        String.format("Attempt %d of %d.", retryAttempts,
                                downloaderConfig.getMaxRetryAttempts()),
                        reliableResourceStatus.getBytesRead(), downloadIdentifier);
                delay();
                reliableResourceCallable = retrieveResource(bytesRead);
                continue;
            }
            retryAttempts++;
            LOGGER.debug("Download attempt {}", retryAttempts);
            try {
                downloadExecutor = Executors.newSingleThreadExecutor();
                downloadFuture = downloadExecutor.submit(reliableResourceCallable);

                // Update callable and its Future in the ReliableResourceInputStream being read
                // by the client so that if client cancels this download the proper Callable and
                // Future are canceled.
                streamReadByClient.setCallableAndItsFuture(reliableResourceCallable, downloadFuture);

                // Monitor to watch that bytes are continually being read from the resource's
                // InputStream. This monitor is used to detect if there are long pauses or
                // network connection loss during the product retrieval. If such a "gap" is
                // detected, the Callable will be canceled and a new download attempt (retry)
                // will be started.
                final Timer downloadTimer = new Timer();
                resourceRetrievalMonitor = new ResourceRetrievalMonitor(downloadFuture,
                        reliableResourceCallable, downloaderConfig.getMonitorPeriodMS(), eventPublisher,
                        resourceResponse, metacard, downloadIdentifier);
                LOGGER.debug("Configuring resourceRetrievalMonitor to run every {} ms",
                        downloaderConfig.getMonitorPeriodMS());
                downloadTimer.scheduleAtFixedRate(resourceRetrievalMonitor,
                        downloaderConfig.getMonitorInitialDelayMS(), downloaderConfig.getMonitorPeriodMS());
                downloadStarted.set(Boolean.TRUE);
                reliableResourceStatus = downloadFuture.get();
            } catch (InterruptedException | CancellationException | ExecutionException e) {
                LOGGER.error("{} - Unable to store product file {}", e.getClass().getSimpleName(), filePath, e);
                reliableResourceStatus = reliableResourceCallable.getReliableResourceStatus();
            }

            LOGGER.debug("reliableResourceStatus = {}", reliableResourceStatus);

            if (DownloadStatus.RESOURCE_DOWNLOAD_COMPLETE.equals(reliableResourceStatus.getDownloadStatus())) {
                LOGGER.debug("Cancelling resourceRetrievalMonitor");
                resourceRetrievalMonitor.cancel();
                if (downloadState.getDownloadState() != DownloadState.CANCELED) {
                    LOGGER.debug("Sending Product Retrieval Complete event");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.COMPLETE,
                            metacard, null, reliableResourceStatus.getBytesRead(), downloadIdentifier);
                } else {
                    LOGGER.debug(
                            "Client had canceled download and caching completed - do NOT send ProductRetrievalCompleted notification");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.COMPLETE,
                            metacard, null, reliableResourceStatus.getBytesRead(), downloadIdentifier, false,
                            true);
                }
                if (doCaching) {
                    LOGGER.debug("Setting reliableResource size");
                    reliableResource.setSize(reliableResourceStatus.getBytesRead());
                    LOGGER.debug("Adding caching key = {} to cache map", reliableResource.getKey());
                    resourceCache.put(reliableResource);
                }
                break;
            } else {
                bytesRead = reliableResourceStatus.getBytesRead();
                LOGGER.debug("Download not complete, only read {} bytes", bytesRead);
                if (fos != null) {
                    fos.flush();
                }

                // Synchronized so that the Callable is not shutdown while in the middle of
                // writing to the
                // FileBackedOutputStream and cache file (need to keep both of these in sync
                // with number of bytes
                // written to each of them).
                synchronized (lock) {

                    // Simply doing Future.cancel(true) or a plain shutdown() is not enough.
                    // The downloadExecutor (or its underlying Future/thread) is holding on
                    // to a resource or is blocking on a read - undetermined at this point,
                    // but shutdownNow() along with re-instantiating the executor at top of
                    // while loop fixes this.
                    downloadExecutor.shutdownNow();
                }

                if (DownloadStatus.PRODUCT_INPUT_STREAM_EXCEPTION
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Detected exception when reading from product's InputStream - re-retrieve
                    // product from the Source and retry caching it
                    LOGGER.info("Handling product InputStream exception");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING,
                            metacard,
                            String.format("Attempt %d of %d.", retryAttempts,
                                    downloaderConfig.getMaxRetryAttempts()),
                            reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    IOUtils.closeQuietly(resourceInputStream);
                    resourceInputStream = null;
                    delay();
                    reliableResourceCallable = retrieveResource(bytesRead);
                } else if (DownloadStatus.CACHED_FILE_OUTPUT_STREAM_EXCEPTION
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Detected exception when writing the product data to the product cache
                    // directory - assume this OutputStream cannot be fixed (e.g., disk full)
                    // and just continue streaming product to the client, i.e., writing to the
                    // FileBackedOutputStream
                    LOGGER.info("Handling FileOutputStream exception");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING,
                            metacard,
                            String.format("Attempt %d of %d.", retryAttempts,
                                    downloaderConfig.getMaxRetryAttempts()),
                            reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    if (doCaching) {
                        deleteCacheFile(fos);
                        resourceCache.removePendingCacheEntry(reliableResource.getKey());
                        // Disable caching since the cache file being written to had issues
                        downloaderConfig.setCacheEnabled(false);
                        doCaching = false;
                        downloadState.setCacheEnabled(downloaderConfig.isCacheEnabled());
                        downloadState.setContinueCaching(doCaching);
                    }
                    reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, countingFbos,
                            downloaderConfig.getChunkSize(), lock);
                    reliableResourceCallable.setBytesRead(bytesRead);

                } else if (DownloadStatus.CLIENT_OUTPUT_STREAM_EXCEPTION
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Detected exception when writing product data to the output stream
                    // (FileBackedOutputStream) that
                    // is being read by the client - assume this is unrecoverable, but continue
                    // to cache the file
                    LOGGER.info("Handling FileBackedOutputStream exception");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.CANCELLED,
                            metacard, "", reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    IOUtils.closeQuietly(fbos);
                    IOUtils.closeQuietly(countingFbos);
                    LOGGER.debug("Cancelling resourceRetrievalMonitor");
                    resourceRetrievalMonitor.cancel();
                    reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, fos,
                            downloaderConfig.getChunkSize(), lock);
                    reliableResourceCallable.setBytesRead(bytesRead);

                } else if (DownloadStatus.RESOURCE_DOWNLOAD_CANCELED
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    LOGGER.info("Handling client cancellation of product download");
                    downloadState.setDownloadState(DownloadState.CANCELED);
                    LOGGER.debug("Cancelling resourceRetrievalMonitor");
                    resourceRetrievalMonitor.cancel();
                    eventListener.removeDownloadIdentifier(downloadIdentifier);
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.CANCELLED,
                            metacard, "", reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    if (doCaching && downloaderConfig.isCacheWhenCanceled()) {
                        LOGGER.debug("Continuing to cache product");
                        reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, fos,
                                downloaderConfig.getChunkSize(), lock);
                        reliableResourceCallable.setBytesRead(bytesRead);
                    } else {
                        break;
                    }

                } else if (DownloadStatus.RESOURCE_DOWNLOAD_INTERRUPTED
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Caching has been interrupted (possibly resourceRetrievalMonitor detected
                    // too much time being taken to retrieve a chunk of product data from the
                    // InputStream) - re-retrieve product from the Source, skip forward in the
                    // product InputStream the number of bytes already read successfully, and
                    // retry caching it
                    LOGGER.info("Handling interrupt of product caching - closing source InputStream");

                    // Set InputStream used on previous attempt to null so that any attempt to
                    // close it will not fail (CXF's DelegatingInputStream, which is the
                    // underlying InputStream being used, does a consume() which is a read() as
                    // part of its close() operation and this will result in a blocking read)
                    resourceInputStream = null;
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING,
                            metacard,
                            String.format("Attempt %d of %d.", retryAttempts,
                                    downloaderConfig.getMaxRetryAttempts()),
                            reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    delay();
                    reliableResourceCallable = retrieveResource(bytesRead);
                }
            }
        }

        if (null != reliableResourceStatus && !DownloadStatus.RESOURCE_DOWNLOAD_COMPLETE
                .equals(reliableResourceStatus.getDownloadStatus())) {
            if (doCaching) {
                deleteCacheFile(fos);
            }
            if (!DownloadStatus.RESOURCE_DOWNLOAD_CANCELED.equals(reliableResourceStatus.getDownloadStatus())) {
                eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.FAILED, metacard,
                        "Unable to retrieve product file.", reliableResourceStatus.getBytesRead(),
                        downloadIdentifier);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Unable to store product file {}", filePath, e);
        downloadState.setDownloadState(DownloadState.FAILED);
        eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.FAILED, metacard,
                "Unable to store product file.", reliableResourceStatus.getBytesRead(), downloadIdentifier);
    } finally {
        cleanupAfterDownload(reliableResourceStatus);
        downloadExecutor.shutdown();
    }
}

From source file:com.corporatetaxi.TaxiArrived_Acitivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_taxiarrived);
    taxiArrived_AcitivityInstance = this;
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);//from  w  w  w.  j  ava  2  s  . com
    // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);
    txt_header = (TextView) findViewById(R.id.textheader);
    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    fab_boarded = (FloatingActionButton) findViewById(R.id.fab_boarded);
    fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    taxinamehead = (TextView) findViewById(R.id.taxinamehead);
    taxiname = (TextView) findViewById(R.id.taxinametext);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");
    txt_header.setTypeface(tf);

    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);
    taxinamehead.setTypeface(tf);
    taxiname.setTypeface(tf);
    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);
    /////back arrow ////////////
    //        final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
    //        upArrow.setColorFilter(getResources().getColor(R.color.colorbutton), PorterDuff.Mode.SRC_ATOP);
    //        getSupportActionBar().setHomeAsUpIndicator(upArrow);

    ////////current date time//////////////////
    currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    Log.d("currentdatetime", currentDateTimeString);
    //caceldialog();
    /////////////notification data///////////////
    Intent intent = getIntent();
    String data = intent.getStringExtra("data");

    Log.d("data value", data + "");
    try {
        JSONObject jsonObject = new JSONObject(data);
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        // driverlatitude = jsonObject.getDouble("latitude");
        //driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        tripamount = jsonObject.getString("amount");
        Log.d("amooo", tripamount);
        tripdestination = jsonObject.getString("destination");
        corporateusercompany = jsonObject.getString("corporatecompany");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        Log.d("driveriamge", driverimage);
        Log.d("longitudeeeee:------", String.valueOf(jsonObject.getDouble("longitude")));

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        taxiname.setText(drivertaxiname);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }
        if (driverimage.equalsIgnoreCase("")) {
            mdriverimage.setImageResource(R.drawable.ic_action_user);
        } else {
            Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                    .resize(200, 200).into(mdriverimage);
        }

        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiArrived_Acitivity.this)),
                            new Double(AppPreferences.getCurrentlong(TaxiArrived_Acitivity.this)));
                        MarkerOptions marker2 = new MarkerOptions().position(loc2);
                        map.clear();
                        marker2.icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi));
                        map.addMarker(marker2.title(drivername));*/
                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiArrived_Acitivity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiArrived_Acitivity.this)));

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                    }
                });

            }
        }, delay, period);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    ////////////notification dataend///////////////
    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();
        }
    });
    fab_boarded.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent1 = new Intent(TaxiArrived_Acitivity.this, Payment_Activity.class);

            intent1.putExtra("driver_companyname", drivercompanyname);
            intent1.putExtra("trip_amount", tripamount);
            intent1.putExtra("trip_destination", tripdestination);
            intent1.putExtra("user_company", corporateusercompany);
            intent1.putExtra("driver_image", driverimage);
            intent1.putExtra("drver_name", drivername);
            intent1.putExtra("driver_mobile", drivermobile);
            intent1.putExtra("driver_taxinumber", drivertexinumber);
            intent1.putExtra("driver_taxiname", drivertaxiname);
            startActivity(intent1);

            new BoardeTripAsynch().execute();

        }
    });
    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });

}

From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java

@Override
protected Void doInBackground(Integer... params) {
    try {/*  w ww  . j  a  v a 2  s.c  o m*/
        URL url = new URL(mUrl);
        Log.d(LOG_TAG, "MXMediaDownloadWorkerTask " + this + " starts");

        mDownloadStats = new IMXMediaDownloadListener.DownloadStats();
        // don't known yet
        mDownloadStats.mEstimatedRemainingTime = -1;

        InputStream stream = null;

        int filelen = -1;
        URLConnection connection = null;

        try {
            connection = url.openConnection();

            if (mHsConfig != null && connection instanceof HttpsURLConnection) {
                // Add SSL Socket factory.
                HttpsURLConnection sslConn = (HttpsURLConnection) connection;
                try {
                    Pair<SSLSocketFactory, X509TrustManager> pair = CertUtil
                            .newPinnedSSLSocketFactory(mHsConfig);
                    sslConn.setSSLSocketFactory(pair.first);
                    sslConn.setHostnameVerifier(CertUtil.newHostnameVerifier(mHsConfig));
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground SSL exception " + e.getLocalizedMessage());
                }
            }

            // add a timeout to avoid infinite loading display.
            connection.setReadTimeout(DOWNLOAD_TIME_OUT);
            filelen = connection.getContentLength();
            stream = connection.getInputStream();
        } catch (Exception e) {
            Log.e(LOG_TAG, "bitmapForURL : fail to open the connection " + e.getMessage());

            InputStream errorStream = ((HttpsURLConnection) connection).getErrorStream();

            if (null != errorStream) {
                try {
                    BufferedReader streamReader = new BufferedReader(
                            new InputStreamReader(errorStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();

                    String inputStr;

                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }

                    mErrorAsJsonElement = new JsonParser().parse(responseStrBuilder.toString());
                } catch (Exception ee) {
                    Log.e(LOG_TAG, "bitmapForURL : Error parsing error " + ee.getLocalizedMessage());
                }
            }

            // privacy
            //Log.d(LOG_TAG, "MediaWorkerTask " + mUrl + " does not exist");
            Log.d(LOG_TAG, "MediaWorkerTask an url does not exist");

            // if some medias are not found
            // do not try to reload them until the next application launch.
            synchronized (mUnreachableUrls) {
                mUnreachableUrls.add(mUrl);
            }
        }

        dispatchDownloadStart();

        // test if the download has not been cancelled
        if (!isDownloadCancelled() && (null == mErrorAsJsonElement)) {

            final long startDownloadTime = System.currentTimeMillis();

            String filename = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType) + ".tmp";
            FileOutputStream fos = new FileOutputStream(new File(mDirectoryFile, filename));

            mDownloadStats.mDownloadId = mUrl;
            mDownloadStats.mProgress = 0;
            mDownloadStats.mDownloadedSize = 0;
            mDownloadStats.mFileSize = filelen;
            mDownloadStats.mElapsedTime = 0;
            mDownloadStats.mEstimatedRemainingTime = -1;
            mDownloadStats.mBitRate = 0;

            final android.os.Handler uiHandler = new android.os.Handler(Looper.getMainLooper());

            final Timer refreshTimer = new Timer();

            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    refreshTimer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            uiHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (!mIsDone) {
                                        publishProgress(startDownloadTime);
                                    }
                                }
                            });
                        }
                    }, new java.util.Date(), 100);
                }
            });

            try {
                byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE];
                int len;
                while (!isDownloadCancelled() && (len = stream.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                    mDownloadStats.mDownloadedSize += len;
                }

                if (!isDownloadCancelled()) {
                    mDownloadStats.mProgress = 100;
                }
            } catch (OutOfMemoryError outOfMemoryError) {
                Log.e(LOG_TAG, "doInBackground: out of memory");
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground fail to read image " + e.getMessage());
            }

            mIsDone = true;

            close(stream);
            fos.flush();
            fos.close();

            if (null != mEncryptedFileInfo) {
                File file = new File(mDirectoryFile, filename);
                FileInputStream fis = new FileInputStream(file);
                InputStream is = MXEncryptedAttachments.decryptAttachment(fis, mEncryptedFileInfo);
                fis.close();

                // if the decryption succeeds, replace the encrypted file content by the unencrypted one
                if (null != is) {
                    mApplicationContext.deleteFile(filename);

                    fos = new FileOutputStream(file);
                    byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE];
                    int len;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                } else {
                    mDownloadStats.mProgress = 0;
                }
            }

            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    refreshTimer.cancel();
                }
            });

            if ((null != connection) && (connection instanceof HttpsURLConnection)) {
                ((HttpsURLConnection) connection).disconnect();
            }

            // the file has been successfully downloaded
            if (mDownloadStats.mProgress == 100) {
                try {
                    File originalFile = new File(mDirectoryFile, filename);
                    String newFileName = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType);
                    File newFile = new File(mDirectoryFile, newFileName);
                    if (newFile.exists()) {
                        // Or you could throw here.
                        mApplicationContext.deleteFile(newFileName);
                    }
                    originalFile.renameTo(newFile);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground : renaming error " + e.getLocalizedMessage());
                }
            }
        }

        if (mDownloadStats.mProgress == 100) {
            Log.d(LOG_TAG, "The download " + this + " is done.");
        } else {
            if (null != mErrorAsJsonElement) {
                Log.d(LOG_TAG, "The download " + this + " failed : mErrorAsJsonElement "
                        + mErrorAsJsonElement.toString());
            } else {
                Log.d(LOG_TAG, "The download " + this + " failed.");
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to download media " + this);
    }

    // remove the image from the loading one
    synchronized (mPendingDownloadByUrl) {
        mPendingDownloadByUrl.remove(mUrl);
    }

    return null;
}

From source file:com.anp.bdmt.MainActivity.java

private void pageSwitcher(final ViewPager viewPager) {

    int second = 2 * 1000;

    final Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override//from   w  ww  .  ja v  a 2 s .  c om
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int position = viewPager.getCurrentItem();

                    if (position == 0) {
                        viewPager.setCurrentItem(1);
                    } else if (position == 1) {
                        viewPager.setCurrentItem(0);
                    }
                }
            });

        }
    }, 0, second);
}