Example usage for android.content Intent ACTION_BATTERY_CHANGED

List of usage examples for android.content Intent ACTION_BATTERY_CHANGED

Introduction

In this page you can find the example usage for android.content Intent ACTION_BATTERY_CHANGED.

Prototype

String ACTION_BATTERY_CHANGED

To view the source code for android.content Intent ACTION_BATTERY_CHANGED.

Click Source Link

Document

Broadcast Action: This is a sticky broadcast containing the charging state, level, and other information about the battery.

Usage

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

private void monitorBatteryState() {
    battReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            StringBuilder sb = new StringBuilder();

            int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); // charge level from 0 to scale inclusive
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); // Max value for charge level
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
            boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false);
            int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); //0 if the device is not plugged in; 1 if plugged into an AC power adapter; 2 if plugged in via USB.
            //                int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1); // voltage in millivolts
            nBatteryTemp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1); // current battery temperature in tenths of a degree Centigrade
            //                String technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);

            nChargeLevel = -1; // percentage, or -1 for unknown
            if (rawlevel >= 0 && scale > 0) {
                nChargeLevel = (rawlevel * 100) / scale;
            }// w  w w  .  ja va  2  s  .  co m

            if (plugged > 0)
                sACStatus = "ONLINE";
            else
                sACStatus = "OFFLINE";

            if (present == false)
                sb.append("NO BATTERY");
            else {
                if (nChargeLevel < 10)
                    sb.append("Critical");
                else if (nChargeLevel < 33)
                    sb.append("LOW");
                else if (nChargeLevel > 80)
                    sb.append("HIGH");
            }

            if (BatteryManager.BATTERY_HEALTH_OVERHEAT == health) {
                sb.append("Overheated ");
                sb.append((((float) (nBatteryTemp)) / 10));
                sb.append("(C)");
            } else {
                switch (status) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    // old emulator; maybe also when plugged in with no battery
                    if (present == true)
                        sb.append(" UNKNOWN");
                    break;
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    sb.append(" CHARGING");
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    sb.append(" DISCHARGING");
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    sb.append(" NOTCHARGING");
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    sb.append(" FULL");
                    break;
                default:
                    if (present == true)
                        sb.append("Unknown");
                    break;
                }
            }

            sPowerStatus = sb.toString();
        }
    };

    IntentFilter battFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(battReceiver, battFilter);
}

From source file:de.j4velin.wifiAutoOff.Preferences.java

@SuppressWarnings("deprecation")
@Override//from  w w  w .ja  va 2  s.c om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    if (BuildConfig.DEBUG && PermissionChecker.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
        requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }

    status = (StatusPreference) findPreference("status");
    status.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(final Preference preference) {
            WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            boolean connected = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
            if (wm.isWifiEnabled() && !connected) {
                try {
                    startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            } else if (!wm.isWifiEnabled()) {
                wm.setWifiEnabled(true);
            } else {
                try {
                    startActivity(
                            new Intent(Settings.ACTION_WIFI_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            }
            return true;
        }
    });

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    final CheckBoxPreference screen_off = (CheckBoxPreference) findPreference("off_screen_off");
    screen_off.setSummary(
            getString(R.string.for_at_least, prefs.getInt("screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF)));

    if (!keepWiFiOn(this)) {
        screen_off.setChecked(false);
    }

    screen_off.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (!keepWiFiOn(Preferences.this)) {
                    new AlertDialog.Builder(Preferences.this).setMessage(R.string.sleep_policy)
                            .setPositiveButton(R.string.adv_wifi_settings, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS)
                                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    } catch (Exception e) {
                                        Toast.makeText(Preferences.this, R.string.settings_not_found_,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }).setNegativeButton(android.R.string.cancel, new OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                    return false;
                }
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, screen_off,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, screen_off, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "screen_off_timeout",
                            Receiver.TIMEOUT_SCREEN_OFF, false);
                }
            }
            return true;
        }
    });

    findPreference("off_no_network").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, preference,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "no_network_timeout", Receiver.TIMEOUT_NO_NETWORK, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, preference, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "no_network_timeout",
                            Receiver.TIMEOUT_NO_NETWORK, false);
                }
            }
            return true;
        }
    });

    final CheckBoxPreference on_at = (CheckBoxPreference) findPreference("on_at");
    on_at.setTitle(getString(R.string.at_summary, prefs.getString("on_at_time", Receiver.ON_AT_TIME)));
    on_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("on_at_time", Receiver.ON_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("on_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        on_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        on_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_on_at_));
                dialog.show();
            }
            return true;
        }
    });

    final CheckBoxPreference off_at = (CheckBoxPreference) findPreference("off_at");
    off_at.setTitle(getString(R.string.at_summary, prefs.getString("off_at_time", Receiver.OFF_AT_TIME)));
    off_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("off_at_time", Receiver.OFF_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("off_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        off_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        off_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_off_at_));
                dialog.show();
            }
            return true;
        }
    });

    final Preference on_every = findPreference("on_every");
    final String[] time_names = getResources().getStringArray(R.array.time_names);
    // default 2 hours
    on_every.setTitle(getString(R.string.every_summary, prefs.getString("on_every_str", time_names[4])));
    on_every.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Preferences.this);
                builder.setTitle(R.string.turn_wifi_on_every).setItems(time_names,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                prefs.edit().putInt("on_every_time_min", time_values[which])
                                        .putString("on_every_str", time_names[which]).commit();
                                on_every.setTitle(getString(R.string.every_summary, time_names[which]));
                            }
                        });
                builder.create().show();
            }
            return true;
        }
    });

    Preference locations = findPreference("locations");
    if (BuildConfig.FLAVOR.equals("play")) {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK)) {
            locations.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(final Preference preference) {
                    startActivity(new Intent(Preferences.this, Locations.class));
                    return true;
                }
            });
        } else {
            locations.setEnabled(false);
        }
    } else {
        locations.setSummary("Not available in F-Droid version");
        locations.setEnabled(false);
    }

    final Preference power = findPreference("power_connected");
    power.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((boolean) newValue) {
                Intent battery = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                if (battery != null && battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0) {
                    // already connected to external power
                    prefs.edit().putBoolean("ignore_screen_off", true).commit();
                }
            } else {
                prefs.edit().putBoolean("ignore_screen_off", false).commit();
            }
            return true;
        }
    });
}

From source file:og.android.tether.MainActivity.java

public void onResume() {
    Log.d(MSG_TAG, "Calling onResume()");
    Log.d(MSG_TAG, "ADVCONFIG " + this.application.settings.getBoolean("configadv", false));
    try {/*from ww w .  j a va 2s  .  c  om*/
        if (getIntent().getData().getPath().equals("/LAUNCH_CHECK")) {
            setIntent(null);
            openLaunchedDialog(false);
        }
    } catch (Exception e) {
    }

    this.showRadioMode();
    super.onResume();
    this.intentFilter = new IntentFilter();

    // Check, if the battery-temperature should be displayed
    if (this.application.settings.getString("batterytemppref", "celsius").equals("disabled") == false) {
        // create the IntentFilter that will be used to listen
        // to battery status broadcasts
        this.intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        this.batteryTemperatureLayout.setVisibility(View.VISIBLE);
    } else {
        this.batteryTemperatureLayout.setVisibility(View.INVISIBLE);
    }

    this.intentFilter.addAction(TetherService.INTENT_TRAFFIC);
    this.intentFilter.addAction(TetherService.INTENT_STATE);
    this.intentFilter.addAction(RSSReader.MESSAGE_JSON_RSS);
    this.intentFilter.addAction(TetherApplication.MESSAGE_POST_STATS);
    registerReceiver(this.intentReceiver, this.intentFilter);
    this.toggleStartStop();

    // Check, if the lockbutton should be displayed
    if (this.stopTblRow.getVisibility() == View.VISIBLE
            && this.application.settings.getBoolean("lockscreenpref", true) == false) {
        this.lockButtonCheckbox.setVisibility(View.VISIBLE);
    } else {
        this.lockButtonCheckbox.setVisibility(View.GONE);
    }

    this.rssPanel.setOpen(!this.application.settings.getBoolean("rss_closed", false), true);
    hideCommunityText(!this.rssPanel.isOpen());

    this.rssReader.readRSS();
}

From source file:saphion.services.ForegroundService.java

public Status readBatteryStat() {
    Intent batteryIntent = getBaseContext().registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    double scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    int plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    isconnected = (plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB
            || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS);
    level = -1;// ww  w  .  j a  v  a2 s  .c  om
    if (rawlevel >= 0 && scale > 0) {
        level = (int) ((rawlevel * 100) / scale);
        Log.d("rawLevel: " + rawlevel);
        Log.d("scale: " + scale);
    }

    if (mPref.getBoolean(PreferenceHelper.KEY_ONE_PERCENT_HACK, false)) {
        try {
            java.io.FileReader fReader = new java.io.FileReader(
                    "/sys/class/power_supply/battery/charge_counter");
            java.io.BufferedReader bReader = new java.io.BufferedReader(fReader);
            int charge_counter = Integer.valueOf(bReader.readLine());
            bReader.close();

            if (charge_counter > PreferenceHelper.CHARGE_COUNTER_LEGIT_MAX) {
                disableOnePercentHack("charge_counter is too big to be actual charge");
            } else {
                if (charge_counter > 100)
                    charge_counter = 100;

                level = charge_counter;
            }
        } catch (java.io.FileNotFoundException e) {
            /*
             * These error messages are only really useful to me and might
             * as well be left hardwired here in English.
             */
            disableOnePercentHack("charge_counter file doesn't exist");
        } catch (java.io.IOException e) {
            disableOnePercentHack("Error reading charge_counter file");
        }
    }

    return new Status(level, isconnected);
}

From source file:com.android.settings.HWSettings.java

@Override
public void onResume() {
    super.onResume();

    setActionBarStyle();/*from   w  ww.  j  a  v a2 s .c  o  m*/

    mDevelopmentPreferencesListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            invalidateHeaders();
        }
    };
    mDevelopmentPreferences.registerOnSharedPreferenceChangeListener(mDevelopmentPreferencesListener);
    // SPRD:ADD register receiver.
    ListAdapter listAdapter = getListAdapter();
    if (listAdapter instanceof HeaderAdapter) {
        // add for tab style
        ((HeaderAdapter) listAdapter).flushViewCache();
        // add for tab style
        ((HeaderAdapter) listAdapter).resume();
    }
    // SPRD:ADD update Header
    invalidateHeaders();

    registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

}

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 www  . 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("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  . java 2s. com*/

    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 ww  w.  j a v 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("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);/*from w  w w  .  ja  va2 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("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:org.geometerplus.android.fbreader.FBReader.java

@Override
protected void onResume() {
    super.onResume();

    myStartTimer = true;/*from   w w w . j ava 2 s  .c  om*/
    Config.Instance().runOnConnect(new Runnable() {
        public void run() {
            SyncOperations.enableSync(FBReader.this, myFBReaderApp.SyncOptions);

            final int brightnessLevel = getZLibrary().ScreenBrightnessLevelOption.getValue();
            if (brightnessLevel != 0) {
                setScreenBrightness(brightnessLevel);
            } else {
                setScreenBrightnessAuto();
            }
            if (getZLibrary().DisableButtonLightsOption.getValue()) {
                setButtonLight(false);
            }

            getCollection().bindToService(FBReader.this, new Runnable() {
                public void run() {
                    final BookModel model = myFBReaderApp.Model;
                    if (model == null || model.Book == null) {
                        return;
                    }
                    onPreferencesUpdate(myFBReaderApp.Collection.getBookById(model.Book.getId()));
                }
            });
        }
    });

    registerReceiver(myBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    IsPaused = false;
    myResumeTimestamp = System.currentTimeMillis();
    if (OnResumeAction != null) {
        final Runnable action = OnResumeAction;
        OnResumeAction = null;
        action.run();
    }

    registerReceiver(mySyncUpdateReceiver, new IntentFilter(SyncOperations.UPDATED));

    SetScreenOrientationAction.setOrientation(this, ZLibrary.Instance().getOrientationOption().getValue());
    if (myCancelIntent != null) {
        final Intent intent = myCancelIntent;
        myCancelIntent = null;
        getCollection().bindToService(this, new Runnable() {
            public void run() {
                runCancelAction(intent);
            }
        });
        return;
    } else if (myOpenBookIntent != null) {
        final Intent intent = myOpenBookIntent;
        myOpenBookIntent = null;
        getCollection().bindToService(this, new Runnable() {
            public void run() {
                openBook(intent, null, true);
            }
        });
    } else if (myFBReaderApp.getCurrentServerBook(null) != null) {
        getCollection().bindToService(this, new Runnable() {
            public void run() {
                myFBReaderApp.useSyncInfo(true, FBReader.this);
            }
        });
    } else if (myFBReaderApp.Model == null && myFBReaderApp.ExternalBook != null) {
        getCollection().bindToService(this, new Runnable() {
            public void run() {
                myFBReaderApp.openBook(myFBReaderApp.ExternalBook, null, null, FBReader.this);
            }
        });
    } else {
        getCollection().bindToService(this, new Runnable() {
            public void run() {
                myFBReaderApp.useSyncInfo(true, FBReader.this);
            }
        });
    }

    PopupPanel.restoreVisibilities(myFBReaderApp);
    ApiServerImplementation.sendEvent(this, ApiListener.EVENT_READ_MODE_OPENED);
}