Example usage for android.net.wifi WifiManager createWifiLock

List of usage examples for android.net.wifi WifiManager createWifiLock

Introduction

In this page you can find the example usage for android.net.wifi WifiManager createWifiLock.

Prototype

public WifiLock createWifiLock(int lockType, String tag) 

Source Link

Document

Creates a new WifiLock.

Usage

From source file:cz.babi.android.remoteme.service.ConnectionService.java

@Override
public void onCreate() {
    if (Common.DEBUG)
        Log.d(TAG_CLASS_NAME, "[onCreate]");

    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    /* Lock Wi-Fi, if need so. */
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "WiFiLockTag");
    if (preferences.getBoolean(getString(R.string.pref_name_keep_wifi_alive), true))
        lockWiFi();// ww  w.j av  a  2  s .com

    /* Display a notification about us starting. */
    if (preferences.getBoolean(getString(R.string.pref_name_show_notification), true)) {
        showNotification();
    }
}

From source file:net.simno.klingar.playback.LocalPlayback.java

LocalPlayback(Context context, MusicController musicController, AudioManager audioManager,
        WifiManager wifiManager) {
    this.context = context;
    this.musicController = musicController;
    this.audioManager = audioManager;
    this.wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "klingar_lock");
    this.state = PlaybackStateCompat.STATE_NONE;
    String agent = Util.getUserAgent(context, context.getResources().getString(R.string.app_name));
    this.dataSourceFactory = new DefaultDataSourceFactory(context, agent, null);
    this.extractorsFactory = new DefaultExtractorsFactory();
}

From source file:com.terminal.ide.TermService.java

@Override
public void onCreate() {
    compat = new ServiceForegroundCompat(this);
    mTermSessions = new ArrayList<TermSession>();

    /**// ww w  .j  a va2s  .  co  m
     * ??
     * @author wanghao
     * @date 2015-3-27
     * ???Activity
     */
    //?intent
    //warning??start.class
    //?mainActivity
    Intent openMainActivityIntent = new Intent(this, mainAvtivity.class);
    Intent openTerminalActivityIntent = new Intent(this, Term.class);
    openTerminalActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    openMainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Intent exitTerminalIntent = new Intent(this, ExitService.class);
    Notification sessionBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getText(R.string.application_terminal))
            .setContentText(getText(R.string.service_notify_text))
            .setContentIntent(PendingIntent.getActivity(this, 0, openMainActivityIntent, 0))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getText(R.string.service_notify_text)))
            .addAction(R.drawable.ic_action_iconfont_terminal, getText(R.string.notification_open_termianl),
                    PendingIntent.getActivity(this, 0, openTerminalActivityIntent,
                            Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .addAction(R.drawable.ic_action_iconfont_exit, getText(R.string.notification_exit_app),
                    PendingIntent.getService(this, 0, exitTerminalIntent, 0))
            .setOngoing(true).build();
    compat.startForeground(RUNNING_NOTIFICATION, sessionBuilder);

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs.registerOnSharedPreferenceChangeListener(this);
    mHardKeys.setKeyMappings(mPrefs);

    //Setup the Hard Key Mappings..
    mSettings = new TermSettings(mPrefs);

    //Need to set the HOME Folder and Bash startup..
    //Sometime getfilesdir return NULL ?
    mSessionInit = false;
    File home = getFilesDir();
    if (home != null) {
        initSessions(home);
    }

    //Start a webserver for comms..
    //        mServer = new webserver(this);
    //        mServer.start();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    //Get a wake lock
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
    mScreenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TermDebug.LOG_TAG);
    mWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, TermDebug.LOG_TAG);

    //Get the Initial Values
    //        boolean cpulock     = getStringPref("cpulock","1") == 1 ? true : false;
    //        boolean wifilock    = getStringPref("wifilock","0") == 1 ? true : false;
    //        boolean screenlock  = getStringPref("screenlock","0") == 1 ? true : false;
    setupWakeLocks();

    Log.d(TermDebug.LOG_TAG, "TermService started");

    return;
}

From source file:com.qweex.callisto.podcast.DownloadTask.java

@Override
protected Boolean doInBackground(String... params) {
    String TAG = StaticBlob.TAG();
    boolean isVideo;
    Cursor current;/*from   w w  w. ja  v  a  2s.  c  o m*/

    long id = 0, identity = 0;
    Log.e(TAG, "Preparing to start: " + StaticBlob.databaseConnector.getActiveDownloads().getCount()
            + " downloads");
    boolean canceled = false;
    while (StaticBlob.databaseConnector.getActiveDownloads().getCount() > 0) {
        if (isCancelled()) //Checks to see if it has been canceled by somewhere else
        {
            mNotificationManager.cancel(NOTIFICATION_ID);
            return false;
        }
        try {
            Cursor c = StaticBlob.databaseConnector.getActiveDownloads();
            c.moveToFirst();
            id = c.getLong(c.getColumnIndex("_id"));
            identity = c.getLong(c.getColumnIndex("identity"));
            isVideo = c.getInt(c.getColumnIndex("video")) > 0;
            current = StaticBlob.databaseConnector.getOneEpisode(identity);
            current.moveToFirst();

            //Get info
            AudLink = current.getString(current.getColumnIndex("mp3link"));
            VidLink = current.getString(current.getColumnIndex("vidlink"));
            AudSize = current.getLong(current.getColumnIndex("mp3size"));
            VidSize = current.getLong(current.getColumnIndex("vidsize"));
            Title = current.getString(current.getColumnIndex("title"));
            Date = current.getString(current.getColumnIndex("date"));
            Show = current.getString(current.getColumnIndex("show"));
            Date = StaticBlob.sdfFile.format(StaticBlob.sdfRaw.parse(Date));

            //Getting target
            Target = new File(StaticBlob.storage_path + File.separator + Show);
            Target.mkdirs();
            if (Title.indexOf("|") > 0)
                Title = Title.substring(0, Title.indexOf("|"));
            Title = Title.trim();
            AudFile = new File(Target,
                    Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(AudLink));
            if (VidLink != null)
                VidFile = new File(Target,
                        Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(VidLink));
            Target = isVideo ? VidFile : AudFile;

            //Prepare the HTTP
            Log.i(TAG, "Path: " + Target.getPath());
            URL url = new URL(isVideo ? VidLink : AudLink);
            Log.i(TAG, "Starting download: " + url.toString());

            Log.i(TAG, "Opening the connection...");
            HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
            String lastModified = ucon.getHeaderField("Last-Modified");
            ucon = (HttpURLConnection) url.openConnection();
            if (Target.exists()) {
                ucon.setRequestProperty("Range", "bytes=" + Target.length() + "-");
                ucon.setRequestProperty("If-Range", lastModified);
            }
            ucon.setReadTimeout(TIMEOUT_CONNECTION);
            ucon.setConnectTimeout(TIMEOUT_SOCKET);
            ucon.connect();

            //Notification
            mBuilder.setProgress(100, 0, true)
                    .setContentTitle(this.context.getResources().getString(R.string.downloading) + " "
                            + StaticBlob.current_download + " "
                            + this.context.getResources().getString(R.string.of) + " " + downloading_count)
                    .setContentText(Show + ": " + Title);
            // Displays the progress bar for the first time.
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

            //Actually do the DLing
            InputStream is = ucon.getInputStream();
            TotalSize = ucon.getContentLength() + Target.length();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
            FileOutputStream outStream;
            byte buff[];
            Log.i(TAG, "mmk skipping the downloaded portion..." + Target.length() + " of " + TotalSize);
            if (Target.exists()) //Append if it exists
                outStream = new FileOutputStream(Target, true);
            else
                outStream = new FileOutputStream(Target);
            buff = new byte[5 * 1024];
            Log.i(TAG, "Getting content length (size)");
            int len = 0;
            long downloadedSize = Target.length(), percentDone = 0;

            //SPEED_COUNT == the number of times through the buffer loop to go through before updating the speed
            // currentDownloadLoopIndex == ???
            // lastTime == The time that the last speed was calculated at
            // all_spds == All speeds tabulated thus far from currentDownloadLoopIndex to SPEED_COUNT
            // avg_speed == the average speed when SPEED_COUNT is reached
            int SPEED_COUNT = 200, currentDownloadLoopIndex = 0;
            long lastTime = (new java.util.Date()).getTime(), all_spds = 0;
            double avg_speed = 0;
            DecimalFormat df = new DecimalFormat("#.##");

            //Wifi lock
            WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (DownloadList.Download_wifiLock == null)
                DownloadList.Download_wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL,
                        "Callisto_download");
            if (!DownloadList.Download_wifiLock.isHeld())
                DownloadList.Download_wifiLock.acquire();

            Log.i(TAG, "FINALLY starting the download");
            inner_failures = 0;
            //-----------------Here is where the actual downloading happens----------------
            while (len != -1) {
                Cursor active = StaticBlob.databaseConnector.getActiveDownloads();
                if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0)
                    canceled = true;
                else {
                    active.moveToFirst();
                    canceled = active.getLong(active.getColumnIndex("identity")) != identity;
                }
                if (canceled) {
                    Log.i(TAG, "Download has been canceled, deleting.");
                    Target.delete();
                    break;
                }
                if (isCancelled()) {
                    mNotificationManager.cancel(NOTIFICATION_ID);
                    return false;
                }

                try {
                    len = inStream.read(buff);
                    if (len == -1)
                        break;

                    outStream.write(buff, 0, len);
                    downloadedSize += len;
                    percentDone = downloadedSize * 100;
                    percentDone /= TotalSize;

                    //Add to the average speed
                    long temp_spd = 0;
                    long time_diff = ((new java.util.Date()).getTime() - lastTime);
                    if (time_diff > 0) {
                        temp_spd = len * 100 / time_diff;
                        currentDownloadLoopIndex++;
                        all_spds += temp_spd;
                        lastTime = (new java.util.Date()).getTime();
                    }

                } catch (IOException e) {
                    Log.e(TAG + ":IOException", "IO is a moon - " + inner_failures);
                    inner_failures++;
                    if (inner_failures == INNER_LIMIT)
                        break;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                    }
                    //Add failure to average
                    currentDownloadLoopIndex++;
                    lastTime = (new java.util.Date()).getTime();

                } catch (Exception e) {
                    Log.e(TAG + ":??Exception", e.getClass() + " : " + e.getMessage());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                    }
                    //Add failure to average
                    currentDownloadLoopIndex++;
                    lastTime = (new java.util.Date()).getTime();
                }

                //If the time is right, get the average
                if (currentDownloadLoopIndex >= SPEED_COUNT) {
                    avg_speed = all_spds * 1.0 / currentDownloadLoopIndex / 100;
                    all_spds = 0;
                    currentDownloadLoopIndex = 0;

                    if (DownloadList.thisInstance != null) {
                        DownloadList.thisInstance.runOnUiThread(
                                DownloadList.thisInstance.new DownloadProgressUpdater((int) (TotalSize / 1000),
                                        (int) (downloadedSize / 1000)));
                    }

                    mBuilder.setProgress((int) (TotalSize / 1000), (int) (downloadedSize / 1000), false)
                            .setContentTitle(this.context.getResources().getString(R.string.downloading) + " "
                                    + StaticBlob.current_download + " "
                                    + this.context.getResources().getString(R.string.of) + " "
                                    + downloading_count + " - " + percentDone + "%  (" + df.format(avg_speed)
                                    + "kb/s)")
                            .setContentText(Show + ": " + Title);
                    // Displays the progress bar for the first time.
                    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                }
            } // END download of single file

            outStream.flush();
            outStream.close();
            inStream.close();
            if (inner_failures == INNER_LIMIT) {
                throw new Exception("Inner exception has passed " + INNER_LIMIT);
            }

            Cursor active = StaticBlob.databaseConnector.getActiveDownloads();
            if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0)
                canceled = true;
            else {
                active.moveToFirst();
                canceled = active.getLong(active.getColumnIndex("identity")) != identity;
            }
            if (!canceled) {
                Log.i(TAG, "Trying to finish with " + Target.length() + "==" + TotalSize);
                if (Target.length() == TotalSize) {
                    StaticBlob.current_download++;

                    Log.i(TAG, (inner_failures < INNER_LIMIT ? "Successfully" : "FAILED") + " downloaded to : "
                            + Target.getPath());

                    //Move the download from active to completed.
                    StaticBlob.databaseConnector.markDownloadComplete(id);

                    Log.i(TAG, " " + DownloadList.rebuildHeaderThings);
                    if (DownloadList.rebuildHeaderThings != null)
                        DownloadList.rebuildHeaderThings.sendEmptyMessage(0);

                    boolean queue = PreferenceManager.getDefaultSharedPreferences(context)
                            .getBoolean("download_to_queue", false);
                    if (queue) {
                        StaticBlob.databaseConnector.appendToQueue(identity, false, isVideo);
                        StaticBlob.playerInfo.update(context);
                    }
                    //Episode Desc
                    if (EpisodeDesc.currentInstance != null)
                        EpisodeDesc.currentInstance.determineButtons();
                    //ShowList
                    if (ShowList.thisInstance != null && ShowList.thisInstance.currentDownloadItem != null) {
                        ShowList.thisInstance.runOnUiThread(ShowList.thisInstance.new updateBoldOrItalic(id,
                                ShowList.thisInstance.currentDownloadItem, AudFile, VidFile, AudSize, VidSize));
                        ShowList.thisInstance.currentDownloadItem = null;
                    }
                }
            } else
                Target.delete();
        } catch (ParseException e) {
            Log.e(TAG + ":ParseException", "Error parsing a date from the SQLite db: ");
            Log.e(TAG + ":ParseException", Date);
            Log.e(TAG + ":ParseException", "(This should never happen).");
            outer_failures++;
            e.printStackTrace();
        } catch (Exception e) {
            outer_failures++;
            Log.e(TAG + ":Exception " + e.getClass(), "[" + outer_failures + "] Msg: " + e.getMessage());
            e.printStackTrace();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
            }
        }
        if (outer_failures == OUTER_LIMIT) {
            boolean quit = false;
            //if(quit = aDownloads.charAt(1)=='x')
            //    aDownloads = aDownloads.replaceAll("x","");
            quit = true;
            if (DownloadList.rebuildHeaderThings != null)
                DownloadList.rebuildHeaderThings.sendEmptyMessage(0);
            failed++;
            outer_failures = 0;

            if (quit)
                break;
        }
    }
    Log.i(TAG, "Finished Downloading");
    if (DownloadList.thisInstance != null)
        DownloadList.thisInstance.updateMenu();

    //Wifi lock
    if (DownloadList.Download_wifiLock != null && DownloadList.Download_wifiLock.isHeld())
        DownloadList.Download_wifiLock.release();

    //Notification
    mNotificationManager.cancel(NOTIFICATION_ID);
    if (downloading_count > 0) {

        mBuilder.setProgress(100, 0, false)
                .setContentTitle("Finished downloading " + downloading_count + " files");
        if (failed > 0)
            mBuilder.setContentText(failed + " failed, try them again later");
        mBuilder.setAutoCancel(true);
        mBuilder.setOngoing(false);

        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        StaticBlob.current_download = 1;
        downloading_count = 0;
    } else {
        StaticBlob.current_download = 1;
        downloading_count = 0;
        return false;
    }
    return true;
}

From source file:de.schildbach.wallet.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);//w  w w.j  a  va  2s .c o m

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        blockStore.getChainHead(); // detect corruptions as early as possible

        final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();

        if (!blockChainFileExists && earliestKeyCreationTime > 0) {
            try {
                final InputStream checkpointsInputStream = getAssets().open(Constants.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore,
                        earliestKeyCreationTime);
            } catch (final IOException x) {
                // continue without checkpoints
                x.printStackTrace();
            }
        }
    } catch (final BlockStoreException x) {
        try {
            blockStore = new BoundedOverheadBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
            blockStore.getChainHead(); // detect corruptions as early as possible
        } catch (final BlockStoreException x2) {
            blockChainFile.delete();

            x2.printStackTrace();
            throw new Error("blockstore cannot be created", x2);
        }
    }

    Log.i(TAG, "using " + blockStore.getClass().getName());

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

From source file:com.feathercoin.wallet.feathercoin.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);// w w w .j a  v a 2s . c  o  m

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        copyBlockchainSnapshot(blockChainFile);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        if (!blockChainFileExists) { // Starting from scratch
            try {
                final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
                final InputStream checkpointsFileIn = getAssets().open("checkpoints");
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsFileIn, blockStore,
                        earliestKeyCreationTime);
            } catch (IOException e) {
                Log.d("Feathercoin", "Couldn't find checkpoints file; starting from genesis");
            }
        }
        blockStore.getChainHead(); // detect corruptions as early as possible
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    } catch (final NullPointerException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    }

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

From source file:de.schildbach.wallet.digitalcoin.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);//w ww.  j  av a  2 s  .  c  o  m

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        copyBlockchainSnapshot(blockChainFile);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        if (!blockChainFileExists) { // Starting from scratch
            try {
                final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
                final InputStream checkpointsFileIn = getAssets().open("checkpoints");
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsFileIn, blockStore,
                        earliestKeyCreationTime);
            } catch (IOException e) {
                Log.d("digitalcoin", "Couldn't find checkpoints file; starting from genesis");
            }
        }
        blockStore.getChainHead(); // detect corruptions as early as possible
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    } catch (final NullPointerException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    }

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

From source file:de.schildbach.wallet.worldcoin.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);//from  w ww.  jav  a  2  s.c  om

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        copyBlockchainSnapshot(blockChainFile);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        if (!blockChainFileExists) { // Starting from scratch
            try {
                final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
                final InputStream checkpointsFileIn = getAssets().open("checkpoints");
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsFileIn, blockStore,
                        earliestKeyCreationTime);
            } catch (IOException e) {
                Log.d("worldcoin", "Couldn't find checkpoints file; starting from genesis");
            }
        }
        blockStore.getChainHead(); // detect corruptions as early as possible
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    } catch (final NullPointerException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    }

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

From source file:de.schildbach.wallet.goldcoin.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);//  w ww.ja v a  2s  .c o  m

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        copyBlockchainSnapshot(blockChainFile);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        if (!blockChainFileExists) { // Starting from scratch
            try {
                final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
                final InputStream checkpointsFileIn = getAssets().open("checkpoints");
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsFileIn, blockStore,
                        earliestKeyCreationTime);
            } catch (IOException e) {
                Log.d("Litecoin", "Couldn't find checkpoints file; starting from genesis");
            }
        }
        blockStore.getChainHead(); // detect corruptions as early as possible
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    } catch (final NullPointerException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    }

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

From source file:de.schildbach.wallet.marscoin.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);/*from   w w w  .jav a  2  s . c  o m*/

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        copyBlockchainSnapshot(blockChainFile);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        if (!blockChainFileExists) { // Starting from scratch
            try {
                final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
                final InputStream checkpointsFileIn = getAssets().open("checkpoints");
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsFileIn, blockStore,
                        earliestKeyCreationTime);
            } catch (IOException e) {
                Log.d("marscoin", "Couldn't find checkpoints file; starting from genesis");
            }
        }
        blockStore.getChainHead(); // detect corruptions as early as possible
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    } catch (final NullPointerException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    }

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}