Example usage for android.media AudioManager STREAM_VOICE_CALL

List of usage examples for android.media AudioManager STREAM_VOICE_CALL

Introduction

In this page you can find the example usage for android.media AudioManager STREAM_VOICE_CALL.

Prototype

int STREAM_VOICE_CALL

To view the source code for android.media AudioManager STREAM_VOICE_CALL.

Click Source Link

Document

Used to identify the volume of audio streams for phone calls

Usage

From source file:Main.java

public static int getVolumeMax(Context context) {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    return audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
}

From source file:org.saydroid.tether.usb.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (((Engine) Engine.getInstance()).getConfigurationService().getBoolean(SgsConfigurationEntry.GENERAL_DSO,
            SgsConfigurationEntry.DEFAULT_GENERAL_DSO)) {
        setRequestedOrientation(Configuration.ORIENTATION_PORTRAIT);
    }/*from  w  ww  . j  a v a2  s. c o  m*/

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    mHandler = new Handler();
    setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);

    if (!Engine.getInstance().isStarted()) {
        startActivityForResult(new Intent(this, ScreenSplash.class), MainActivity.RC_SPLASH);
        return;
    }

    Bundle bundle = savedInstanceState;
    if (bundle == null) {
        Intent intent = getIntent();
        bundle = intent == null ? null : intent.getExtras();
    }
    if (bundle != null && bundle.getInt("action", MainActivity.ACTION_NONE) != MainActivity.ACTION_NONE) {
        handleAction(bundle);
    } else if (mScreenService != null) {
        mScreenService.show(ScreenHome.class);
    }
}

From source file:com.google.android.car.kitchensink.volume.VolumeTestFragment.java

private static String streamToName(int stream) {
    switch (stream) {
    case AudioManager.STREAM_ALARM:
        return "Alarm";
    case AudioManager.STREAM_MUSIC:
        return "Music";
    case AudioManager.STREAM_NOTIFICATION:
        return "Notification";
    case AudioManager.STREAM_RING:
        return "Ring";
    case AudioManager.STREAM_VOICE_CALL:
        return "Call";
    case AudioManager.STREAM_SYSTEM:
        return "System";
    default:/*from   w w  w.j  a v  a2  s  .  c o m*/
        return "Unknown";
    }
}

From source file:de.tubs.ibr.dtn.dtalkie.service.TalkieService.java

@Override
public void onCreate() {
    // call onCreate of the super-class
    super.onCreate();

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

    // get the audio-manager
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(mPrefListener);

    // create message database
    mDatabase = new MessageDatabase(this);

    // init sound pool
    mSoundManager = new SoundFXManager(AudioManager.STREAM_VOICE_CALL, 2);

    mSoundManager.load(this, Sound.BEEP);
    mSoundManager.load(this, Sound.CONFIRM);
    mSoundManager.load(this, Sound.QUIT);
    mSoundManager.load(this, Sound.RING);
    mSoundManager.load(this, Sound.SQUELSH_LONG);
    mSoundManager.load(this, Sound.SQUELSH_SHORT);

    // create a player
    mPlayer = new MediaPlayer();
    mPlayer.setOnCompletionListener(mCompletionListener);
    mPlayer.setOnPreparedListener(mPrepareListener);

    // create registration
    Registration reg = new Registration("dtalkie");
    reg.add(RecorderService.TALKIE_GROUP_EID);

    // register own data handler for incoming bundles
    mClient = new DTNClient(_session_listener);

    try {//w w w .  j av a 2 s.  co  m
        mClient.initialize(this, reg);
        mServiceError = ServiceError.NO_ERROR;
    } catch (ServiceNotAvailableException e) {
        mServiceError = ServiceError.SERVICE_NOT_FOUND;
    } catch (SecurityException ex) {
        mServiceError = ServiceError.PERMISSION_NOT_GRANTED;
    }

    Log.d(TAG, "Service created.");

    if (prefs.getBoolean("autoplay", false) || HeadsetService.ENABLED) {
        Intent play_i = new Intent(TalkieService.this, TalkieService.class);
        play_i.setAction(TalkieService.ACTION_PLAY_NEXT);
        startService(play_i);
    }
}

From source file:im.vector.activity.CallViewActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // assume that the user cancels the call if it is ringing
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (!canCallBeResumed()) {
            if (null != mCall) {
                mCall.hangup("");
            }/*from w ww  .  j  ava2 s  . c  o  m*/
        } else {
            saveCallView();
        }
    } else if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) || (keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
        // this is a trick to reduce the ring volume :
        // when the call is ringing, the AudioManager.Mode switch to MODE_IN_COMMUNICATION
        // so the volume is the next call one whereas the user expects to reduce the ring volume.
        if ((null != mCall) && mCall.getCallState().equals(IMXCall.CALL_STATE_RINGING)) {
            AudioManager audioManager = (AudioManager) CallViewActivity.this
                    .getSystemService(Context.AUDIO_SERVICE);
            // IMXChrome call issue
            if (audioManager.getMode() == AudioManager.MODE_IN_COMMUNICATION) {
                int musicVol = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL)
                        * audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
                        / audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVol, 0);
            }
        }
    }

    return super.onKeyDown(keyCode, event);
}

From source file:com.morlunk.mumbleclient.app.PlumbleActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    mSettings = Settings.getInstance(this);
    setTheme(mSettings.getTheme());//from   w  w w . ja va2 s.  co m

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setStayAwake(mSettings.shouldStayAwake());

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    preferences.registerOnSharedPreferenceChangeListener(this);

    mDatabase = new PlumbleSQLiteDatabase(this); // TODO add support for cloud storage
    mDatabase.open();

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    mDrawerList.setOnItemClickListener(this);
    mDrawerAdapter = new DrawerAdapter(this, this);
    mDrawerList.setAdapter(mDrawerAdapter);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            super.onDrawerStateChanged(newState);
            // Prevent push to talk from getting stuck on when the drawer is opened.
            if (getService() != null && getService().isSynchronized() && getService().isTalking()
                    && !mSettings.isPushToTalkToggle()) {
                getService().setTalkingState(false);
            }
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            supportInvalidateOptionsMenu();
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // Tint logo to theme
    int iconColor = getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimaryInverse })
            .getColor(0, -1);
    Drawable logo = getResources().getDrawable(R.drawable.ic_home);
    logo.setColorFilter(iconColor, PorterDuff.Mode.MULTIPLY);
    getSupportActionBar().setLogo(logo);

    AlertDialog.Builder dadb = new AlertDialog.Builder(this);
    dadb.setMessage(R.string.disconnectSure);
    dadb.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (mService != null && mService.isConnectionEstablished())
                mService.disconnect();
            loadDrawerFragment(DrawerAdapter.ITEM_FAVOURITES);
        }
    });
    dadb.setNegativeButton(android.R.string.cancel, null);
    mDisconnectPromptBuilder = dadb;

    if (savedInstanceState == null) {
        if (getIntent() != null && getIntent().hasExtra(EXTRA_DRAWER_FRAGMENT)) {
            loadDrawerFragment(getIntent().getIntExtra(EXTRA_DRAWER_FRAGMENT, DrawerAdapter.ITEM_FAVOURITES));
        } else {
            loadDrawerFragment(DrawerAdapter.ITEM_FAVOURITES);
        }
    }

    // If we're given a Mumble URL to show, open up a server edit fragment.
    if (getIntent() != null && Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        String url = getIntent().getDataString();
        try {
            Server server = MumbleURLParser.parseURL(url);

            // Open a dialog prompting the user to connect to the Mumble server.
            DialogFragment fragment = (DialogFragment) ServerEditFragment.createServerEditDialog(
                    PlumbleActivity.this, server, ServerEditFragment.Action.CONNECT_ACTION, true);
            fragment.show(getSupportFragmentManager(), "url_edit");
        } catch (MalformedURLException e) {
            Toast.makeText(this, getString(R.string.mumble_url_parse_failed), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    setVolumeControlStream(
            mSettings.isHandsetMode() ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC);

    if (mSettings.isFirstRun())
        showSetupWizard();
}

From source file:de.tubs.ibr.dtn.dtalkie.service.TalkieService.java

@Override
protected void onHandleIntent(Intent intent) {
    String action = intent.getAction();

    if (de.tubs.ibr.dtn.Intent.RECEIVE.equals(action)) {
        try {/*from w ww  . j a v a2s .  com*/
            while (mClient.getSession().queryNext())
                ;
        } catch (Exception e) {
        }
        ;
    } else if (ACTION_MARK_DELIVERED.equals(action)) {
        final BundleID received = intent.getParcelableExtra("bundleid");
        try {
            mClient.getSession().delivered(received);
        } catch (Exception e) {
            Log.e(TAG, "Can not mark bundle as delivered.", e);
        }
    } else if (ACTION_PLAY.equals(action)) {
        Folder f = Folder.valueOf(intent.getStringExtra("folder"));
        Long msgid = intent.getLongExtra("message", 0L);

        // unmark the message
        mDatabase.mark(f, msgid, false);

        try {
            // prepare player
            Message msg = mDatabase.get(f, msgid);
            mPlayer.setDataSource(msg.getFile().getAbsolutePath());
            mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
            mPlayer.prepareAsync();

            synchronized (mPlayerLock) {
                // set the player to playing
                mPlaying = true;

                // wait until the play-back is done
                while (mPlaying) {
                    mPlayerLock.wait();
                }
            }
        } catch (InterruptedException e) {
            Log.e(TAG, null, e);
        } catch (IOException e) {
            Log.e(TAG, null, e);
        }

        // mark the message as played
        mDatabase.mark(f, msgid, true);

        // remove notification is there are no more pending
        // messages
        removeNotification();
    } else if (ACTION_PLAY_NEXT.equals(action)) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(TalkieService.this);
        if (prefs.getBoolean("autoplay", false) || HeadsetService.ENABLED) {
            Message next = mDatabase.nextMarked(Folder.INBOX, false);

            if (next != null) {
                Intent play_i = new Intent(TalkieService.this, TalkieService.class);
                play_i.setAction(TalkieService.ACTION_PLAY);
                play_i.putExtra("folder", Folder.INBOX.toString());
                play_i.putExtra("message", next.getId());
                startService(play_i);
            }
        }
    } else if (ACTION_RECORDED.equals(action)) {
        File recfile = (File) intent.getSerializableExtra("recfile");

        // create a new bundle
        Bundle b = new Bundle();

        // set destination
        b.setDestination((EID) intent.getSerializableExtra("destination"));

        // assign lifetime
        b.setLifetime(1800L);

        // request signing of the message
        b.set(ProcFlags.DTNSEC_REQUEST_SIGN, true);

        try {
            ParcelFileDescriptor fd = ParcelFileDescriptor.open(recfile, ParcelFileDescriptor.MODE_READ_ONLY);
            BundleID ret = mClient.getSession().send(b, fd);

            if (ret == null) {
                Log.e(TAG, "Recording sent failed");
            } else {
                Log.i(TAG, "Recording sent, BundleID: " + ret.toString());
            }

            recfile.delete();
        } catch (FileNotFoundException ex) {
            Log.e(TAG, "Can not open message file for transmission", ex);
        } catch (SessionDestroyedException ex) {
            Log.e(TAG, "DTN session has been destroyed.", ex);
        } catch (Exception e) {
            Log.e(TAG, "Unexpected exception while transmit message.", e);
        }
    } else if (ACTION_RECEIVED.equals(action)) {
        String source = intent.getStringExtra("source");
        String destination = intent.getStringExtra("destination");
        Date created = (Date) intent.getSerializableExtra("created");
        Date received = (Date) intent.getSerializableExtra("received");
        File file = (File) intent.getSerializableExtra("file");

        // add message to database
        Message msg = new Message(source, destination, file);
        msg.setCreated(created);
        msg.setReceived(received);
        mDatabase.put(Folder.INBOX, msg);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (prefs.getBoolean("notification", true)) {
            // create a notification for this message
            createNotification();
        }

        Intent play_i = new Intent(TalkieService.this, TalkieService.class);
        play_i.setAction(ACTION_PLAY_NEXT);
        startService(play_i);
    }
}

From source file:edu.sfsu.csc780.chathub.ui.activities.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DesignUtils.applyColorfulTheme(this);
    setContentView(R.layout.activity_main);
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    // Set default username is anonymous.
    mUsername = ANONYMOUS;// www.j a v  a  2 s  .  c o m
    //Initialize Auth
    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();
    if (mUser == null) {
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mUser.getDisplayName();
        if (mUser.getPhotoUrl() != null) {
            mPhotoUrl = mUser.getPhotoUrl().toString();
        }
    }

    AudioUtil.startAudioListener(this);

    mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext())
            .applicationKey(APIKeys.SINCH_API_KEY).applicationSecret(APIKeys.SINCH_APP_SECRET)
            .environmentHost("sandbox.sinch.com")
            .userId(UserUtil.parseUsername(mSharedPreferences.getString("username", "anonymous"))).build();
    mSinchClient.setSupportCalling(true);

    mCurrentChannel = mSharedPreferences.getString("currentChannel", "general");
    mCurrChanTextView = (TextView) findViewById(R.id.currentChannelName);
    mCurrChanTextView.setText(ChannelUtil.getChannelDisplayName(mCurrentChannel, this));

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API).build();

    // Initialize ProgressBar and RecyclerView.

    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);
    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mChannelAdd = (RelativeLayout) findViewById(R.id.channelAdd);

    mToolBar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolBar);
    mToolBar.setTitleTextColor(Color.WHITE);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mDrawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));

    mFirebaseAdapter = MessageUtil.getFirebaseAdapter(this, this, /* MessageLoadListener */
            mLinearLayoutManager, mMessageRecyclerView, mImageClickListener);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MSG_LENGTH_LIMIT) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (FloatingActionButton) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Send messages on click.
            mMessageRecyclerView.scrollToPosition(0);
            ChatMessage chatMessage = new ChatMessage(mMessageEditText.getText().toString(), mUsername,
                    mPhotoUrl, mCurrentChannel);
            MessageUtil.send(chatMessage, MainActivity.this);
            mMessageEditText.setText("");
        }
    });

    mImageButton = (ImageButton) findViewById(R.id.shareImageButton);
    mImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pickImage();
        }
    });

    mPhotoButton = (ImageButton) findViewById(R.id.cameraButton);
    mPhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePhotoIntent();
        }
    });

    mLocationButton = (ImageButton) findViewById(R.id.locationButton);
    mLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadMap();
        }
    });

    mChannelAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, ChannelSearchActivity.class);
            startActivityForResult(intent, REQUEST_NEW_CHANNEL);
        }
    });

    SearchView jumpSearchView = (SearchView) findViewById(R.id.jumpSearch);
    int id = jumpSearchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    TextView textView = (TextView) jumpSearchView.findViewById(id);
    textView.setTextColor(Color.WHITE);
    textView.setHintTextColor(Color.WHITE);

    jumpSearchView.setIconified(false);
    jumpSearchView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Not implemented", Toast.LENGTH_SHORT).show();
        }
    });

    mNavRecyclerView = (RecyclerView) findViewById(R.id.navRecyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    mNavRecyclerView.setLayoutManager(linearLayoutManager);
    mNavRecyclerView.setAdapter(ChannelUtil.getFirebaseAdapterForUserChannelList(mChannelClickListener,
            mAuth.getCurrentUser().getDisplayName()));

    RecyclerView userListRecyclerView = (RecyclerView) findViewById(R.id.userListRecyclerView);
    LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
    userListRecyclerView.setLayoutManager(linearLayoutManager2);
    userListRecyclerView.setAdapter(UserUtil.getFirebaseAdapterForUserList(mChannelClickListener));

    Button voiceCallButton = (Button) findViewById(R.id.voiceCall);
    mCallProgressTextView = (TextView) findViewById(R.id.callinprogress);

    final AudioManager audioManager = (AudioManager) getApplicationContext()
            .getSystemService(Context.AUDIO_SERVICE);
    voiceCallButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            CallClient callClient = mSinchClient.getCallClient();
            if (canCall) {
                call = callClient.callConference("General");
                call.addCallListener(new CallListener() {
                    @Override
                    public void onCallProgressing(Call call) {
                        //setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                        audioManager.adjustStreamVolume(AudioManager.STREAM_VOICE_CALL,
                                AudioManager.ADJUST_RAISE, 10);
                        Log.d("Call", "Call progressing");
                    }

                    @Override
                    public void onCallEstablished(Call call) {
                        setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                        mCallProgressTextView.setVisibility(View.VISIBLE);
                        Log.d("Call", "Calling now");
                    }

                    @Override
                    public void onCallEnded(Call call) {
                        setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
                        Log.d("Call", "Stopped calling");
                        mCallProgressTextView.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onShouldSendPushNotification(Call call, List<PushPair> list) {
                        Log.d("Call", "Push");
                    }
                });
            }
        }
    });

    Button endCallButton = (Button) findViewById(R.id.endCall);
    endCallButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (call != null) {
                call.hangup();
                call = null;
            }
        }
    });
}

From source file:timer.com.maydaysdk.MayDayVideoCallFragment.java

public void onConnected(RCConnection connection) {
    Log.i(TAG, "RCConnection connected");
    mImageViewFullScreen.setVisibility(View.VISIBLE);
    mImageViewMute.setVisibility(View.VISIBLE);
    // reset to no mute at beginning of new videoChat.
    mMuteAudio = false;//from  w w  w  .j av a2s  .  c  o m
    getActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

@Override
public void onCreate() {
    super.onCreate();
    FileLog.d("=============== VoIPService STARTING ===============");
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
            && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER) != null) {
        int outFramesPerBuffer = Integer
                .parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
        VoIPController.setNativeBufferSize(outFramesPerBuffer);
    } else {//from  w  w  w.  j a v  a 2  s.  c  o m
        VoIPController.setNativeBufferSize(
                AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
                        / 2);
    }
    final SharedPreferences preferences = getSharedPreferences("mainconfig", MODE_PRIVATE);
    VoIPServerConfig.setConfig(preferences.getString("voip_server_config", "{}"));
    if (System.currentTimeMillis() - preferences.getLong("voip_server_config_updated", 0) > 24 * 3600000) {
        ConnectionsManager.getInstance().sendRequest(new TLRPC.TL_phone_getCallConfig(), new RequestDelegate() {
            @Override
            public void run(TLObject response, TLRPC.TL_error error) {
                if (error == null) {
                    String data = ((TLRPC.TL_dataJSON) response).data;
                    VoIPServerConfig.setConfig(data);
                    preferences.edit().putString("voip_server_config", data)
                            .putLong("voip_server_config_updated",
                                    BuildConfig.DEBUG ? 0 : System.currentTimeMillis())
                            .apply();
                }
            }
        });
    }
    try {
        controller = new VoIPController();
        controller.setConnectionStateListener(this);
        controller.setConfig(MessagesController.getInstance().callPacketTimeout / 1000.0,
                MessagesController.getInstance().callConnectTimeout / 1000.0,
                preferences.getInt("VoipDataSaving", VoIPController.DATA_SAVING_NEVER));

        cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE))
                .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
        cpuWakelock.acquire();

        btAdapter = am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ACTION_HEADSET_PLUG);
        if (btAdapter != null) {
            filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
            filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        }
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        filter.addAction(getPackageName() + ".END_CALL");
        filter.addAction(getPackageName() + ".DECLINE_CALL");
        filter.addAction(getPackageName() + ".ANSWER_CALL");
        registerReceiver(receiver, filter);

        ConnectionsManager.getInstance().setAppPaused(false, false);

        soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
        spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
        spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
        spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
        spEndId = soundPool.load(this, R.raw.voip_end, 1);
        spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

        am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

        if (btAdapter != null && btAdapter.isEnabled()) {
            int headsetState = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
            updateBluetoothHeadsetState(headsetState == BluetoothProfile.STATE_CONNECTED);
            if (headsetState == BluetoothProfile.STATE_CONNECTED)
                am.setBluetoothScoOn(true);
            for (StateListener l : stateListeners)
                l.onAudioSettingsChanged();
        }

        NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
    } catch (Exception x) {
        FileLog.e("error initializing voip controller", x);
        callFailed();
    }
}