Example usage for android.content Context POWER_SERVICE

List of usage examples for android.content Context POWER_SERVICE

Introduction

In this page you can find the example usage for android.content Context POWER_SERVICE.

Prototype

String POWER_SERVICE

To view the source code for android.content Context POWER_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.

Usage

From source file:com.zfb.house.emchat.ChatActivity.java

private void setUpView() {
    //??//from  w ww .  j  a va  2  s.co  m
    if (getIntent() != null) {
        toUserBean = (ChatUserBean) getIntent().getSerializableExtra("chatUser");
    }
    /*if(toUserBean==null){//??????
     toUserBean = new ChatUserBean();
     User user = UserUtils.getUserInfo(getIntent().getStringExtra("userId"));
     toUserBean.setUserName(user.getNick());
     toUserBean.setImageUrl();
    }*/
    fromUserBean = new ChatUserBean();

    UserBean localUserBean = UserBean.getInstance(this);
    if (localUserBean != null) {
        fromUserBean.setImageUrl(localUserBean.photo);
        //??  ???    ???
        Log.i("linwb3", "user type = " + localUserBean.userType);
        fromUserBean.setUserType(stringToInteger(localUserBean.userType));
        if (!TextUtils.isEmpty(localUserBean.name)) {
            fromUserBean.setUserName(localUserBean.name);
        } else {
            if (!TextUtils.isEmpty(localUserBean.loginName)) {
                fromUserBean.setUserName(localUserBean.loginName);
            } else {
                if (!TextUtils.isEmpty(localUserBean.phone)) {
                    fromUserBean.setUserName(localUserBean.phone);
                } else {
                    fromUserBean.setUserName("");
                }
            }
        }
    }

    iv_emoticons_normal.setOnClickListener(this);
    iv_emoticons_checked.setOnClickListener(this);
    // position = getIntent().getIntExtra("position", -1);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // ???
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    LogUtils.e("ChatActivity", "chatType==" + chatType);
    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        Map<String, RobotUser> robotMap = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotList();
        if (robotMap != null && robotMap.containsKey(toChatUsername)) {
            isRobot = true;
            String nick = robotMap.get(toChatUsername).getNick();
            if (!TextUtils.isEmpty(nick)) {
                ((TextView) findViewById(R.id.name)).setText(nick);
                Log.e("ChatActivity", "name:" + nick);
            } else {
                ((TextView) findViewById(R.id.name)).setText(toChatUsername);
            }
        } else {
            UserUtils.setUserNick(toChatUsername, (TextView) findViewById(R.id.name));
        }
    } else {
        // ?
        /*      findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
              findViewById(R.id.container_remove).setVisibility(View.GONE);
              findViewById(R.id.container_voice_call).setVisibility(View.GONE);
              findViewById(R.id.container_video_call).setVisibility(View.GONE);
              toChatUsername = getIntent().getStringExtra("groupId");
                
              if(chatType == CHATTYPE_GROUP){
                  onGroupViewCreation();
              }else{ 
                  onChatRoomViewCreation();
              }*/
    }

    // for chatroom type, we only init conversation and create view adapter on success
    if (chatType != CHATTYPE_CHATROOM) {
        onConversationInit();

        onListViewCreation();

        // show forward message if the message is not null
        String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
        if (forward_msg_id != null) {
            // ?????
            forwardMessage(forward_msg_id);
        }
    }
}

From source file:com.wojtechnology.sunami.TheBrain.java

private void init() {
    mSongManager = new SongManager(this);
    mGenreGraph = new GenreGraph(this);
    mSongHistory = new SongHistory(HISTORY_SIZE);
    mShuffleController = new ShuffleController(this, mGenreGraph, mSongManager, mUpNext);
    mMediaPlayer = new MediaPlayer();

    // Setting wake locks
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
    mWakeLock.acquire();//from ww w . j a va 2 s.c o m

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if (!mPreparing) {
                playNext();
            }
        }
    });
    mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            return false;
        }
    });
    mMediaPlayer.setOnPreparedListener(mMPPreparedListener);
    mContext.setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:mintcoin.wallet.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".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);

    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    final Wallet wallet = application.getWallet();

    peerConnectivityListener = new PeerConnectivityListener();

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

    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        log.info("blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        wallet.setLastBlockSeenHeight(-1); // magic value
        wallet.setLastBlockSeenHash(null);
    }

    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 long start = System.currentTimeMillis();
                final InputStream checkpointsInputStream = getAssets()
                        .open(Constants.Files.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore,
                        earliestKeyCreationTime);
                log.info("checkpoints loaded from '{}', took {}ms", Constants.Files.CHECKPOINTS_FILENAME,
                        System.currentTimeMillis() - start);
            } catch (final IOException x) {
                log.error("problem reading checkpoints, continuing without", x);
            }
        }
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        final String msg = "blockstore cannot be created";
        log.error(msg, x);
        throw new Error(msg, x);
    }

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

    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); // implicitly start PeerGroup

    application.getWallet().addEventListener(walletEventListener, Threading.SAME_THREAD);

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

From source file:ca.nehil.rter.streamingapp2.StreamingActivity.java

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

    if (mWakeLock == null) {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL);
        mWakeLock.acquire();//from   w ww.  j a  va 2s  .com
    }

    locationManager.requestLocationUpdates(provider, 0, 1, this);
    // register the overlay control for location updates as well, so we get
    // the geomagnetic field
    locationManager.requestLocationUpdates(provider, 0, 1000, overlay);

    // sensors
    mSensorManager.registerListener(overlay, mAcc, SensorManager.SENSOR_DELAY_NORMAL);
    mSensorManager.registerListener(overlay, mMag, SensorManager.SENSOR_DELAY_NORMAL);

    initLayout();

}

From source file:com.andrew.apollo.MusicPlaybackService.java

private void initService() {
    // Initialize the favorites and recents databases
    mFavoritesCache = FavoritesStore.getInstance(this);
    mRecentsCache = RecentStore.getInstance(this);

    // Initialize the notification helper
    mNotificationHelper = new NotificationHelper(this);

    // Initialize the image fetcher
    mImageFetcher = ImageFetcher.getInstance(this);
    // Initialize the image cache
    mImageFetcher.setImageCache(ImageCache.getInstance(this));

    // Start up the thread running the service. Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block. We also make it
    // background priority so CPU-intensive work will not disrupt the UI.
    final HandlerThread thread = new HandlerThread("MusicPlayerHandler",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();/*w w w  . j a  v  a2  s  .  co  m*/

    // Initialize the handler
    mPlayerHandler = new MusicPlayerHandler(this, thread.getLooper());

    // Initialize the audio manager and register any headset controls for
    // playback
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    try {
        if (mAudioManager != null) {
            mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);
        }
    } catch (SecurityException e) {
        e.printStackTrace();
        // ignore
        // some times the phone does not grant the MODIFY_PHONE_STATE permission
        // this permission is for OMEs and we can't do anything about it
    }

    // Use the remote control APIs to set the playback state
    setUpRemoteControlClient();

    // Initialize the preferences
    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

    // Initialize the media player
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    ConfigurationManager CM = ConfigurationManager.instance();
    // Load Repeat Mode
    setRepeatMode(CM.getInt(Constants.PREF_KEY_GUI_PLAYER_REPEAT_MODE));
    // Load Shuffle Mode On/Off
    enableShuffle(CM.getBoolean(Constants.PREF_KEY_GUI_PLAYER_SHUFFLE_ENABLED));
    MusicUtils.isShuffleEnabled();

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (powerManager != null) {
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        mWakeLock.setReferenceCounted(false);
    }
    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
    shutdownIntent.setAction(SHUTDOWN_ACTION);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    // Listen for the idle state
    scheduleDelayedShutdown();

    // Bring the queue back
    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
    updateNotification();
}

From source file:biz.wiz.android.wallet.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".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);

    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    final Wallet wallet = application.getWallet();

    peerConnectivityListener = new PeerConnectivityListener();

    broadcastPeerState(0);/*  w  w w  .ja  v a 2  s.c o  m*/

    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        log.info("blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        wallet.setLastBlockSeenHeight(-1); // magic value
        wallet.setLastBlockSeenHash(null);
    }

    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.Files.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore,
                        earliestKeyCreationTime);
            } catch (final IOException x) {
                log.error("problem reading checkpoints, continuing without", x);
            }
        }
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        final String msg = "blockstore cannot be created";
        log.error(msg, x);
        throw new Error(msg, x);
    }

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

    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); // implicitly start PeerGroup

    application.getWallet().addEventListener(walletEventListener, Threading.SAME_THREAD);

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

From source file:org.hopestarter.wallet.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".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);

    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    final Wallet wallet = application.getWallet();

    peerConnectivityListener = new PeerConnectivityListener();

    broadcastPeerState(0);//from   w ww.  j a va 2  s .  co  m

    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        log.info("blockchain does not exist, resetting wallet");
        wallet.reset();
    }

    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 long start = System.currentTimeMillis();
                final InputStream checkpointsInputStream = getAssets()
                        .open(Constants.Files.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore,
                        earliestKeyCreationTime);
                log.info("checkpoints loaded from '{}', took {}ms", Constants.Files.CHECKPOINTS_FILENAME,
                        System.currentTimeMillis() - start);
            } catch (final IOException x) {
                log.error("problem reading checkpoints, continuing without", x);
            }
        }
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        final String msg = "blockstore cannot be created";
        log.error(msg, x);
        throw new Error(msg, x);
    }

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

    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); // implicitly start PeerGroup

    application.getWallet().addEventListener(walletEventListener, Threading.SAME_THREAD);

    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);/* w  w  w .  j  a  v  a  2  s.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("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));
}

From source file:de.schildbach.wallet.elysium.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.  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("Elysium", "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.BlockchainService.java

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".onCreate()");

    super.onCreate();
    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);

    peerConnectivityListener = new PeerConnectivityListener();

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

    final WalletBalanceLiveData walletBalance = new WalletBalanceLiveData(application);
    final ExchangeRateLiveData exchangeRate = new ExchangeRateLiveData(application);
    walletBalance.observe(this, new Observer<Coin>() {
        @Override
        public void onChanged(final Coin walletBalance) {
            WalletBalanceWidgetProvider.updateWidgets(BlockchainService.this, walletBalance,
                    exchangeRate.getValue());
        }
    });
    if (Constants.ENABLE_EXCHANGE_RATES) {
        exchangeRate.observe(this, new Observer<ExchangeRate>() {
            @Override
            public void onChanged(final ExchangeRate exchangeRate) {
                final Coin balance = walletBalance.getValue();
                if (balance != null)
                    WalletBalanceWidgetProvider.updateWidgets(BlockchainService.this, balance, exchangeRate);
            }
        });
    }
    wallet = new WalletLiveData(application);
    wallet.observe(this, new Observer<Wallet>() {
        @Override
        public void onChanged(final Wallet wallet) {
            BlockchainService.this.wallet.removeObserver(this);
            final boolean blockChainFileExists = blockChainFile.exists();
            if (!blockChainFileExists) {
                log.info("blockchain does not exist, resetting wallet");
                wallet.reset();
            }

            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 Stopwatch watch = Stopwatch.createStarted();
                        final InputStream checkpointsInputStream = getAssets()
                                .open(Constants.Files.CHECKPOINTS_FILENAME);
                        CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream,
                                blockStore, earliestKeyCreationTime);
                        watch.stop();
                        log.info("checkpoints loaded from '{}', took {}", Constants.Files.CHECKPOINTS_FILENAME,
                                watch);
                    } catch (final IOException x) {
                        log.error("problem reading checkpoints, continuing without", x);
                    }
                }
            } catch (final BlockStoreException x) {
                blockChainFile.delete();

                final String msg = "blockstore cannot be created";
                log.error(msg, x);
                throw new Error(msg, x);
            }

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

            observeLiveDatasThatAreDependentOnWalletAndBlockchain();
        }
    });
}