Example usage for android.net.wifi WifiManager WIFI_MODE_FULL

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

Introduction

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

Prototype

int WIFI_MODE_FULL

To view the source code for android.net.wifi WifiManager WIFI_MODE_FULL.

Click Source Link

Document

In this Wi-Fi lock mode, Wi-Fi will be kept active, and will behave normally, i.e., it will attempt to automatically establish a connection to a remembered access point that is within range, and will do periodic scans if there are remembered access points but none are in range.

Usage

From source file:jackpal.androidterm.Term.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    Log.v(TermDebug.LOG_TAG, "onCreate");

    mPrivateAlias = new ComponentName(this, RemoteInterface.PRIVACT_ACTIVITY_ALIAS);

    if (icicle == null)
        onNewIntent(getIntent());/*from   ww w  . j a  v a2  s. c  om*/

    final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mSettings = new TermSettings(getResources(), mPrefs);
    mPrefs.registerOnSharedPreferenceChangeListener(this);

    boolean vimflavor = this.getPackageName().matches(".*vim.androidterm.*");

    if (!vimflavor && mSettings.doPathExtensions()) {
        mPathReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String path = makePathFromBundle(getResultExtras(false));
                if (intent.getAction().equals(ACTION_PATH_PREPEND_BROADCAST)) {
                    mSettings.setPrependPath(path);
                } else {
                    mSettings.setAppendPath(path);
                }
                mPendingPathBroadcasts--;

                if (mPendingPathBroadcasts <= 0 && mTermService != null) {
                    populateViewFlipper();
                    populateWindowList();
                }
            }
        };

        Intent broadcast = new Intent(ACTION_PATH_BROADCAST);
        if (AndroidCompat.SDK >= 12) {
            broadcast.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
        }
        mPendingPathBroadcasts++;
        sendOrderedBroadcast(broadcast, PERMISSION_PATH_BROADCAST, mPathReceiver, null, RESULT_OK, null, null);

        if (mSettings.allowPathPrepend()) {
            broadcast = new Intent(broadcast);
            broadcast.setAction(ACTION_PATH_PREPEND_BROADCAST);
            mPendingPathBroadcasts++;
            sendOrderedBroadcast(broadcast, PERMISSION_PATH_PREPEND_BROADCAST, mPathReceiver, null, RESULT_OK,
                    null, null);
        }
    }

    TSIntent = new Intent(this, TermService.class);
    startService(TSIntent);

    if (AndroidCompat.SDK >= 11) {
        int theme = mSettings.getColorTheme();
        int actionBarMode = mSettings.actionBarMode();
        mActionBarMode = actionBarMode;
        switch (actionBarMode) {
        case TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE:
            if (theme == 0) {
                setTheme(R.style.Theme_Holo);
            } else {
                setTheme(R.style.Theme_Holo_Light);
            }
            break;
        case TermSettings.ACTION_BAR_MODE_HIDES + 1:
        case TermSettings.ACTION_BAR_MODE_HIDES:
            if (theme == 0) {
                setTheme(R.style.Theme_Holo_ActionBarOverlay);
            } else {
                setTheme(R.style.Theme_Holo_Light_ActionBarOverlay);
            }
            break;
        }
    } else {
        mActionBarMode = TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE;
    }

    setContentView(R.layout.term_activity);
    mViewFlipper = (TermViewFlipper) findViewById(VIEW_FLIPPER);
    setFunctionKeyListener();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    int wifiLockMode = WifiManager.WIFI_MODE_FULL;
    if (AndroidCompat.SDK >= 12) {
        wifiLockMode = WIFI_MODE_FULL_HIGH_PERF;
    }
    mWifiLock = wm.createWifiLock(wifiLockMode, TermDebug.LOG_TAG);

    ActionBarCompat actionBar = ActivityCompat.getActionBar(this);
    if (actionBar != null) {
        mActionBar = actionBar;
        actionBar.setNavigationMode(ActionBarCompat.NAVIGATION_MODE_LIST);
        actionBar.setDisplayOptions(0, ActionBarCompat.DISPLAY_SHOW_TITLE);
        if (mActionBarMode >= TermSettings.ACTION_BAR_MODE_HIDES) {
            actionBar.hide();
        }
    }

    mHaveFullHwKeyboard = checkHaveFullHwKeyboard(getResources().getConfiguration());
    setSoftInputMode(mHaveFullHwKeyboard);

    if (mFunctionBar == -1)
        mFunctionBar = mSettings.showFunctionBar() ? 1 : 0;
    if (mFunctionBar == 1)
        setFunctionBar(mFunctionBar);

    updatePrefs();
    permissionCheckExternalStorage();
    mAlreadyStarted = true;
}

From source file:com.devbrackets.android.playlistcore.service.PlaylistServiceCore.java

/**
 * Used to perform the onCreate functionality when the service is actually created.  This
 * should be overridden instead of {@link #onCreate()} due to a bug in some Samsung devices
 * where {@link #onStartCommand(Intent, int, int)} will get called before {@link #onCreate()}.
 *//*from  ww w.j av a2  s .  co  m*/
protected void onServiceCreate() {
    mediaProgressPoll.setProgressListener(this);
    audioFocusHelper = new AudioFocusHelper(getApplicationContext());
    audioFocusHelper.setAudioFocusCallback(this);

    //Attempts to obtain the wifi lock only if the manifest has requested the permission
    if (getPackageManager().checkPermission(Manifest.permission.WAKE_LOCK,
            getPackageName()) == PackageManager.PERMISSION_GRANTED) {
        wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL, "mcLock");
        wifiLock.setReferenceCounted(false);
    } else {
        Log.w(TAG, "Unable to acquire WAKE_LOCK due to missing manifest permission");
    }

    getPlaylistManager().registerService(this);

    //Another part of the workaround for some Samsung devices
    if (workaroundIntent != null) {
        startService(workaroundIntent);
        workaroundIntent = null;
    }
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public boolean setUpNetwork(String sIniFile) {
    boolean bRet = false;
    int lcv = 0;/*from  ww  w.  jav a 2  s  . c o  m*/
    int lcv2 = 0;
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wc = new WifiConfiguration();
    DoCommand tmpdc = new DoCommand(getApplication());

    String ssid = tmpdc.GetIniData("Network Settings", "SSID", sIniFile);
    String auth = tmpdc.GetIniData("Network Settings", "AUTH", sIniFile);
    String encr = tmpdc.GetIniData("Network Settings", "ENCR", sIniFile);
    String key = tmpdc.GetIniData("Network Settings", "KEY", sIniFile);
    String eap = tmpdc.GetIniData("Network Settings", "EAP", sIniFile);
    String adhoc = tmpdc.GetIniData("Network Settings", "ADHOC", sIniFile);

    Toast.makeText(getApplication().getApplicationContext(), "Starting and configuring network",
            Toast.LENGTH_LONG).show();
    /*
            ContentResolver cr = getContentResolver();
            int nRet;
            try {
    nRet = Settings.System.getInt(cr, Settings.System.WIFI_USE_STATIC_IP);
    String foo2 = "" + nRet;
            } catch (SettingNotFoundException e1) {
    e1.printStackTrace();
            }
    */
    /*
            wc.SSID = "\"Mozilla-Build\"";
            wc.preSharedKey  = "\"MozillaBuildQA500\"";
            wc.hiddenSSID = true;
            wc.status = WifiConfiguration.Status.ENABLED;
            wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    */
    wc.SSID = "\"" + ssid + "\"";
    //        wc.SSID = "\"Mozilla-G\"";
    //        wc.SSID = "\"Mozilla\"";

    if (auth.contentEquals("wpa2")) {
        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wc.preSharedKey = null;
    }

    if (encr.contentEquals("aes")) {
        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    }

    if (eap.contentEquals("peap")) {
        wc.eap.setValue("PEAP");
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
    }

    wc.status = WifiConfiguration.Status.ENABLED;

    if (!wifi.isWifiEnabled())
        wifi.setWifiEnabled(true);

    while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
        Thread.yield();
        if (++lcv > 10000)
            return (bRet);
    }

    wl = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL, "SUTAgent");
    if (wl != null)
        wl.acquire();

    WifiConfiguration foo = null;
    int nNetworkID = -1;

    List<WifiConfiguration> connsLst = wifi.getConfiguredNetworks();
    int nConns = connsLst.size();
    for (int i = 0; i < nConns; i++) {

        foo = connsLst.get(i);
        if (foo.SSID.equalsIgnoreCase(wc.SSID)) {
            nNetworkID = foo.networkId;
            wc.networkId = foo.networkId;
            break;
        }
    }

    int res;

    if (nNetworkID != -1) {
        res = wifi.updateNetwork(wc);
    } else {
        res = wifi.addNetwork(wc);
    }

    Log.d("WifiPreference", "add Network returned " + res);

    boolean b = wifi.enableNetwork(res, true);
    Log.d("WifiPreference", "enableNetwork returned " + b);

    wifi.saveConfiguration();

    WifiInfo wi = wifi.getConnectionInfo();
    SupplicantState ss = wi.getSupplicantState();

    lcv = 0;
    lcv2 = 0;

    while (ss.compareTo(SupplicantState.COMPLETED) != 0) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (wi != null)
            wi = null;
        if (ss != null)
            ss = null;
        wi = wifi.getConnectionInfo();
        ss = wi.getSupplicantState();
        if (++lcv > 60) {
            if (++lcv2 > 5) {
                Toast.makeText(getApplication().getApplicationContext(),
                        "Unable to start and configure network", Toast.LENGTH_LONG).show();
                return (bRet);
            } else {
                Toast.makeText(getApplication().getApplicationContext(), "Resetting wifi interface",
                        Toast.LENGTH_LONG).show();
                if (wl != null)
                    wl.release();
                wifi.setWifiEnabled(false);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
                    Thread.yield();
                }

                wifi.setWifiEnabled(true);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
                    Thread.yield();
                }
                b = wifi.enableNetwork(res, true);
                Log.d("WifiPreference", "enableNetwork returned " + b);
                if (wl != null)
                    wl.acquire();
                lcv = 0;
            }
        }
    }

    lcv = 0;
    while (getLocalIpAddress() == null) {
        if (++lcv > 10000)
            return (bRet);
    }

    Toast.makeText(getApplication().getApplicationContext(), "Network started and configured",
            Toast.LENGTH_LONG).show();
    bRet = true;

    return (bRet);
}

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.  j a va2  s .co  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("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.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);//from  w w  w.  ja v  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("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: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);//from w  ww  .j a v  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("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.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);//ww w .  ja  v a2  s  .  co  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.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);/*  www . jav a2s.co  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:me.spadival.podmode.PodModeService.java

@Override
public void onCreate() {

    IntentFilter usbFilter = new IntentFilter();
    usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    usbFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, usbFilter);
    // mProvider = RemoteMetadataProvider.getInstance(this);

    // mProvider.setOnMetadataChangeListener(mMetadataListner);
    // mProvider.acquireRemoteControls();
    LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter notifyFilter = new IntentFilter();
    notifyFilter.addAction(NOTIFYACTION);
    bManager.registerReceiver(mNotifyReceiver, notifyFilter);

    mSerialHost = new FTDriver((UsbManager) getSystemService(Context.USB_SERVICE));

    mSerialDevice = new FT311UARTInterface(this, null);

    // Get the local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    mBluetoothDevice = null;/*from w w  w  .  j  a v a  2 s . c o m*/

    /*   // If there are paired devices, add each one to the ArrayAdapter
       if (pairedDevices.size() > 0) {
          for (BluetoothDevice device : pairedDevices) {
    if (device.getName().equals("PodModeBT"))
       mBluetoothDevice = device;
          }
       }
            
       if (mBluetoothDevice != null) {
          mBTDevice = new BluetoothSerialService(this, mHandler);
          mBTDevice.connect(mBluetoothDevice);
       } */

    // Create the Wifi lock (this does not acquire the lock, this just
    // creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Create the retriever and start an asynchronous task that will prepare
    // it.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mRetriever = new MusicRetriever(getContentResolver(), getApplicationContext(), true, prefs);

    // mRetriever.switchToMainPlaylist();

    prefs.registerOnSharedPreferenceChangeListener((OnSharedPreferenceChangeListener) this);

    mNowPlaying = prefs.getInt("nowplaying", 0);

    String mBaudrate = prefs.getString("baud_rate", "57600");

    if (mBaudrate.equals("57600"))
        mSerialBaudRate = FTDriver.BAUD57600;
    else if (mBaudrate.equals("38400"))
        mSerialBaudRate = FTDriver.BAUD38400;
    else if (mBaudrate.equals("19200"))
        mSerialBaudRate = FTDriver.BAUD19200;

    (new PrepareMusicRetrieverTask(mRetriever, this)).execute();

    // create the Audio Focus Helper, if the Audio Focus feature is
    // available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always
    // "have" audio focus

    boolean wakeLockPreferred = prefs.getBoolean("wakelock", false);

    if (podWakeLock == null && wakeLockPreferred) {
        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        podWakeLock = powerMgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKETAG);
        podWakeLock.acquire();
    }

    PackageManager pxm = getPackageManager();
    Intent mediaIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

    List<ResolveInfo> mAppsInfo = pxm.queryBroadcastReceivers(mediaIntent, 0);

    mSimpleRemoteApp = prefs.getString("selectapp", null);
    mAdvancedRemoteApp = prefs.getString("selectadvancedapp", PACKAGENAME);

    // Make sure App preferences are still valid and Apps haven't been
    // uninstalled.

    if (mAppsInfo.size() > 0) {

        CharSequence[] entryValues = new CharSequence[mAppsInfo.size()];
        CharSequence[] advEntryValues = new CharSequence[mAppsInfo.size() + 1];

        advEntryValues[0] = PACKAGENAME;

        int i = 0;
        for (ResolveInfo info : mAppsInfo) {
            entryValues[i] = (String) info.activityInfo.packageName;
            advEntryValues[i + 1] = (String) info.activityInfo.packageName;

            i++;
        }

        boolean entryFound = false;

        if (mSimpleRemoteApp != null) {
            for (i = 0; i < entryValues.length; i++) {
                if (mSimpleRemoteApp.equals(entryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectapp", (String) entryValues[0]);
            editor.commit();
            mSimpleRemoteApp = (String) entryValues[0];
        }

        entryFound = false;

        if (mAdvancedRemoteApp != null) {
            for (i = 0; i < advEntryValues.length; i++) {
                if (mAdvancedRemoteApp.equals(advEntryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectadvancedapp", (String) advEntryValues[0]);
            editor.commit();
            mAdvancedRemoteApp = (String) advEntryValues[0];

        }
    } else {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("selectadvancedapp", PACKAGENAME);
        editor.commit();
        mAdvancedRemoteApp = PACKAGENAME;
    }

    mAccessoryName = prefs.getString("accessoryName", null);
    mAccessoryMnf = prefs.getString("accessoryMnf", null);
    mAccessoryModel = prefs.getString("accessoryModel", null);

}

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  .  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("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));
}