Example usage for android.content Context AUDIO_SERVICE

List of usage examples for android.content Context AUDIO_SERVICE

Introduction

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

Prototype

String AUDIO_SERVICE

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

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.media.AudioManager for handling management of volume, ringer modes and audio routing.

Usage

From source file:net.sourceforge.kalimbaradio.androidapp.util.Util.java

public static void unregisterMediaButtonEventReceiver(Context context) {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    ComponentName mediaButtonIntentReceiver = new ComponentName(context.getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    audioManager.unregisterMediaButtonEventReceiver(mediaButtonIntentReceiver);
}

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

/**
 * Init the buttons layer/* ww  w . java 2  s.c om*/
 */
private void manageSubViews() {
    // sanity check
    // the call could have been destroyed between call.
    if (null == mCall) {
        Log.d(LOG_TAG, "manageSubViews nothing to do");
        return;
    }

    // initialize buttons
    if (null == mAcceptRejectLayout) {
        mAcceptRejectLayout = findViewById(R.id.layout_accept_reject);
        mAcceptButton = (Button) findViewById(R.id.accept_button);
        mRejectButton = (Button) findViewById(R.id.reject_button);
        mCancelButton = (Button) findViewById(R.id.cancel_button);
        mStopButton = (Button) findViewById(R.id.stop_button);
        mSpeakerSelectionView = (ImageView) findViewById(R.id.call_speaker_view);

        mCallStateTextView = (TextView) findViewById(R.id.call_state_text);

        mAcceptButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mCall) {
                    mCall.answer();
                }
            }
        });

        mRejectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onHangUp();
            }
        });

        mCancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onHangUp();
            }
        });

        mStopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onHangUp();
            }
        });

        mSpeakerSelectionView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mCall) {
                    mCall.toggleSpeaker();
                    refreshSpeakerButton();
                }
            }
        });

        updateStateTextView("", false);
    }

    String callState = mCall.getCallState();

    Log.d(LOG_TAG, "manageSubViews callState : " + callState);

    // hide / show avatar
    ImageView avatarView = (ImageView) CallViewActivity.this.findViewById(R.id.call_other_member);
    if (null != avatarView) {
        avatarView.setVisibility(
                (callState.equals(IMXCall.CALL_STATE_CONNECTED) && mCall.isVideo()) ? View.GONE : View.VISIBLE);
    }

    refreshSpeakerButton();

    // display the button according to the call state
    if (callState.equals(IMXCall.CALL_STATE_ENDED)) {
        mAcceptRejectLayout.setVisibility(View.GONE);
        mCancelButton.setVisibility(View.GONE);
        mStopButton.setVisibility(View.GONE);
    } else if (callState.equals(IMXCall.CALL_STATE_CONNECTED)) {
        mAcceptRejectLayout.setVisibility(View.GONE);
        mCancelButton.setVisibility(View.GONE);
        mStopButton.setVisibility(View.VISIBLE);
    } else {
        mAcceptRejectLayout.setVisibility(mCall.isIncoming() ? View.VISIBLE : View.GONE);
        mCancelButton.setVisibility(mCall.isIncoming() ? View.GONE : View.VISIBLE);
        mStopButton.setVisibility(View.GONE);
    }

    // display the callview only when the preview is displayed
    if (mCall.isVideo() && !callState.equals(IMXCall.CALL_STATE_ENDED)) {
        int visibility;

        if (callState.equals(IMXCall.CALL_STATE_WAIT_CREATE_OFFER)
                || callState.equals(IMXCall.CALL_STATE_INVITE_SENT)
                || callState.equals(IMXCall.CALL_STATE_RINGING)
                || callState.equals(IMXCall.CALL_STATE_CREATE_ANSWER)
                || callState.equals(IMXCall.CALL_STATE_CONNECTING)
                || callState.equals(IMXCall.CALL_STATE_CONNECTED)) {
            visibility = View.VISIBLE;
        } else {
            visibility = View.GONE;
        }

        if ((null != mCall) && (visibility != mCall.getVisibility())) {
            mCall.setVisibility(visibility);
        }
    }

    // display the callstate
    if (callState.equals(IMXCall.CALL_STATE_CONNECTING) || callState.equals(IMXCall.CALL_STATE_CREATE_ANSWER)
            || callState.equals(IMXCall.CALL_STATE_WAIT_LOCAL_MEDIA)
            || callState.equals(IMXCall.CALL_STATE_WAIT_CREATE_OFFER)) {
        mAcceptButton.setAlpha(0.5f);
        mAcceptButton.setEnabled(false);
        updateStateTextView(getResources().getString(R.string.call_connecting), true);
        mCallStateTextView.setVisibility(View.VISIBLE);
        stopRinging();
    } else if (callState.equals(IMXCall.CALL_STATE_CONNECTED)) {
        stopRinging();

        CallViewActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AudioManager audioManager = (AudioManager) CallViewActivity.this
                        .getSystemService(Context.AUDIO_SERVICE);
                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mCallVolume, 0);
                MXCallsManager.setSpeakerphoneOn(CallViewActivity.this, mCall.isVideo());
                refreshSpeakerButton();
            }
        });

        updateStateTextView(getResources().getString(R.string.call_connected), false);
        mCallStateTextView.setVisibility(mCall.isVideo() ? View.GONE : View.VISIBLE);
    } else if (callState.equals(IMXCall.CALL_STATE_ENDED)) {
        updateStateTextView(getResources().getString(R.string.call_ended), true);
        mCallStateTextView.setVisibility(View.VISIBLE);
    } else if (callState.equals(IMXCall.CALL_STATE_RINGING)) {
        if (mCall.isIncoming()) {
            if (mCall.isVideo()) {
                updateStateTextView(getResources().getString(R.string.incoming_video_call), true);
            } else {
                updateStateTextView(getResources().getString(R.string.incoming_voice_call), true);
            }
        } else {
            updateStateTextView(getResources().getString(R.string.call_ring), true);
        }
        mCallStateTextView.setVisibility(View.VISIBLE);

        if (mAutoAccept) {
            mAutoAccept = false;
            mAcceptButton.setAlpha(0.5f);
            mAcceptButton.setEnabled(false);
            mCallStateTextView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mCall.answer();
                }
            }, 100);
        } else {
            mAcceptButton.setAlpha(1.0f);
            mAcceptButton.setEnabled(true);

            if (mCall.isIncoming()) {
                startRinging(CallViewActivity.this);
            } else {
                startRingbackSound(CallViewActivity.this);
            }
        }
    }
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/**
 * In the case where the test is started through adb command, this method will change the
 * settings if any parameter is specified.
 *///from   w  w  w  .ja  va  2s  . c  o  m
private void runIntentTest() {
    // mIntentRunning == true if test is started through adb command.
    if (mIntentRunning) {
        if (mIntentBufferTestDuration > 0) {
            getApp().setBufferTestDuration(mIntentBufferTestDuration);
        }

        if (mIntentAudioLevel >= 0) {
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            am.setStreamVolume(AudioManager.STREAM_MUSIC, mIntentAudioLevel, 0);
        }

        if (mIntentSamplingRate != 0) {
            getApp().setSamplingRate(mIntentSamplingRate);
        }

        if (mIntentMicSource >= 0) {
            getApp().setMicSource(mIntentMicSource);
        }

        if (mIntentAudioThread >= 0) {
            getApp().setAudioThreadType(mIntentAudioThread);
            getApp().computeDefaults();
        }

        int bytesPerFrame = Constant.BYTES_PER_FRAME;

        if (mIntentRecorderBuffer > 0) {
            getApp().setRecorderBufferSizeInBytes(mIntentRecorderBuffer * bytesPerFrame);
        }

        if (mIntentPlayerBuffer > 0) {
            getApp().setPlayerBufferSizeInBytes(mIntentPlayerBuffer * bytesPerFrame);
        }

        refreshState();

        if (mIntentTestType >= 0) {
            switch (mIntentTestType) {
            case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_LATENCY:
                startLatencyTest();
                break;
            case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_BUFFER_PERIOD:
                startBufferTest();
                break;
            default:
                assert (false);
            }
        } else {
            // if test type is not specified in command, just run latency test
            startLatencyTest();
        }

    }
}

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   w  w w  .ja  v  a  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:leoisasmendi.android.com.suricatepodcast.services.MediaPlayerService.java

private boolean requestAudioFocus() {
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        //Focus gained
        return true;
    }/*from   w ww  . j a v  a2s  .  com*/
    //Could not gain focus
    return false;
}

From source file:com.fastbootmobile.encore.service.PlaybackService.java

/**
 * Request the audio focus and registers the remote media controller
 *//*from   w w  w  .  ja va  2 s. c  o  m*/
private synchronized void requestAudioFocus() {
    if (!mHasAudioFocus) {
        final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        // Request audio focus for music playback
        int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            am.registerMediaButtonEventReceiver(RemoteControlReceiver.getComponentName(this));

            // Notify the remote metadata that we're getting active
            mRemoteMetadata.setActive(true);

            // Register AUDIO_BECOMING_NOISY to stop playback when earbuds are pulled
            registerReceiver(mAudioNoisyReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));

            // Add a WakeLock to avoid CPU going to sleep while music is playing
            mWakeLock.acquire();

            mHasAudioFocus = true;
        } else {
            Log.e(TAG, "Audio focus request denied: " + result);
        }
    }
}

From source file:com.trigger_context.Main_Service.java

private boolean testConditions(String mac) {
    SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE);
    Map<String, ?> cond_map = conditions.getAll();
    Set<String> key_set = cond_map.keySet();
    boolean takeAction = true;
    if (key_set.contains("bluetooth")) {
        // checking the current state against the state set by the user
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        takeAction = new Boolean(bluetoothAdapter.isEnabled())
                .equals(conditions.getString("bluetooth", "false"));
    }//from w w w.  jav  a  2s  .  c  om
    if (takeAction && key_set.contains("wifi")) {
        final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        takeAction = new Boolean(wm.isWifiEnabled()) == conditions.getBoolean("wifi", false);
    }

    if (takeAction && key_set.contains("gps")) {
        final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        takeAction = new Boolean(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                .equals(conditions.getString("gps", "false"));
    }
    if (takeAction && key_set.contains("sms")) {
        final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
        Cursor c = getContentResolver().query(SMS_INBOX, null, "read = 0", null, null);
        if (c != null) {
            int unreadMessagesCount = c.getCount();
            c.close();
            takeAction = new Boolean(unreadMessagesCount > 0).equals(conditions.getString("sms", "false"));
        } else {
            takeAction = false;
        }
    }

    // "NOT TESTED" head set, missed call, accelerometer, proximity, gyro,
    // orientation
    if (takeAction && key_set.contains("headset")) {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        takeAction = am.isMusicActive() == conditions.getBoolean("headset", false);
        // am.isWiredHeadsetOn() is deprecated

    }
    /*
     * if(takeAction && key_set.contains("missedCall")) { final String[]
     * projection = null; final String selection = null; final String[]
     * selectionArgs = null; final String sortOrder =
     * android.provider.CallLog.Calls.DATE + " DESC"; Cursor cursor = null;
     * try{ cursor = getApplicationContext().getContentResolver().query(
     * Uri.parse("content://call_log/calls"), projection, selection,
     * selectionArgs, sortOrder); while (cursor.moveToNext()) { String
     * callLogID =
     * cursor.getString(cursor.getColumnIndex(android.provider.CallLog
     * .Calls._ID)); String callNumber =
     * cursor.getString(cursor.getColumnIndex
     * (android.provider.CallLog.Calls.NUMBER)); String callDate =
     * cursor.getString
     * (cursor.getColumnIndex(android.provider.CallLog.Calls.DATE)); String
     * callType =
     * cursor.getString(cursor.getColumnIndex(android.provider.CallLog
     * .Calls.TYPE)); String isCallNew =
     * cursor.getString(cursor.getColumnIndex
     * (android.provider.CallLog.Calls.NEW)); if(Integer.parseInt(callType)
     * == android.provider.CallLog.Calls.MISSED_CALL_TYPE &&
     * Integer.parseInt(isCallNew) > 0){
     * 
     * } } }catch(Exception ex){ }finally{ cursor.close(); }
     * 
     * }
     */
    return takeAction;
}

From source file:com.hhunj.hhudata.ForegroundService.java

private MediaPlayer ring() throws Exception, IOException {

    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    MediaPlayer player = new MediaPlayer();

    player.setDataSource(this, alert);

    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {

        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

        player.setLooping(true);//ww  w  .  j  av a 2s .  co  m

        player.prepare();

        player.start();

    }

    return player;

}

From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java

private void finishActivity() {
    Log.d(TAG, "finishActivity()");
    runOnUiThread(new Runnable() {
        @Override//from ww  w.j  a  va 2s. c  om
        public void run() {
            LauncherSettings.getInstance(getApplicationContext()).setCurrentPlayingBroadcastType(null);

            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            if (mText2Speech != null) {
                mText2Speech.shutdown();
            }
            mText2Speech = null;
            mText2SpeechHandler = null;
            mBroadcastPayloadIdx = -1;

            if (mWebView != null) {
                mWebView.removeAllViews();
                mWebView.destroy();
            }
            mWebViewClient = null;
            mWebView = null;
            LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mBroadcastReceiver);
            unregisterReceiver(mBroadcastReceiver);

            releaseCpuLock();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSystemUI();
                }
            });

            AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, mStreamMusicVolume, AudioManager.FLAG_PLAY_SOUND);

            //finish();
            Log.e(TAG, "RealtimeBroadcastActivity.java call System.exit(0)");
            System.exit(0);
        }
    });
}

From source file:com.cyanogenmod.eleven.MusicPlaybackService.java

/**
 * {@inheritDoc}//from  w  w  w  . j  av  a2s . c  o  m
 */
@Override
public void onCreate() {
    if (D)
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Initialize the favorites and recents databases
    mRecentsCache = RecentStore.getInstance(this);

    // gets the song play count cache
    mSongPlayCountCache = SongPlayCount.getInstance(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(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.
    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    // Initialize the handler
    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.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());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

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

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

    registerExternalStorageListener();

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

    // 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(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    // Get events when MediaStore content changes
    mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);

    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
    shutdownIntent.setAction(SHUTDOWN);

    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);
}