Java Code Examples for android.media.AudioManager#registerMediaButtonEventReceiver()

The following examples show how to use android.media.AudioManager#registerMediaButtonEventReceiver() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AvrcpService.java    From Botifier with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);
    mNotifications = new ArrayList<Botification>();

    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);
    mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    mHandler = new Handler(){
        public void handleMessage(Message msg){
            resetNotify(true);
        }
    };
}
 
Example 2
Source File: SettingActivity.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    switch (buttonView.getId()) {
        case R.id.setting_wakeup:
            VoiceMediator.get().setWakeUpMode(isChecked);
            break;
        case R.id.setting_wifi:
            AppConfig.dPreferences.edit().putBoolean(AppConfig.DOWNLOAD_ON_WIFI, isChecked).commit();
            LingjuAudioPlayer.create(this).setNoOnlinePlayInMobileNet(!isChecked);
            break;
        case R.id.allow_wire_bt:
            AppConfig.dPreferences.edit().putBoolean(AppConfig.ALLOW_WIRE, isChecked).commit();
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            if (!isChecked) {
                am.unregisterMediaButtonEventReceiver(new ComponentName(getApplicationContext(), MediaButtonReceiver.class));
            } else {
                am.registerMediaButtonEventReceiver(new ComponentName(getApplicationContext(), MediaButtonReceiver.class));
            }
            break;
        case R.id.setting_shake_for_wake:
            AppConfig.dPreferences.edit().putBoolean(AppConfig.SHAKE_WAKE, isChecked).commit();
            break;
        case R.id.setting_incoming_call_tips_switch:
            mAppConfig.incoming_tips = isChecked;
            AppConfig.dPreferences.edit().putBoolean(AppConfig.INCOMING_TIPS, isChecked).commit();
            break;
        case R.id.setting_receiver_msg_tips_switch:
            mAppConfig.inmsg_tips = isChecked;
            AppConfig.dPreferences.edit().putBoolean(AppConfig.IN_MSG_TIPS, isChecked).commit();
            break;
        case R.id.setting_incoming_speakeron_switch:
            mAppConfig.incoming_speaker_on = isChecked;
            AppConfig.dPreferences.edit().putBoolean(AppConfig.INCOMING_SPEAKER_ON, isChecked).commit();
            break;
    }
}
 
Example 3
Source File: Util.java    From Audinaut with GNU General Public License v3.0 5 votes vote down vote up
public static void registerMediaButtonEventReceiver(Context context) {

        // Only do it if enabled in the settings.
        SharedPreferences prefs = getPreferences(context);
        boolean enabled = prefs.getBoolean(Constants.PREFERENCES_KEY_MEDIA_BUTTONS, true);

        if (enabled) {
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            ComponentName componentName = new ComponentName(context.getPackageName(), MediaButtonIntentReceiver.class.getName());
            audioManager.registerMediaButtonEventReceiver(componentName);
        }
    }
 
Example 4
Source File: HeadSetUtil.java    From HeadSetControl with Apache License 2.0 5 votes vote down vote up
/**
 * 为MEDIA_BUTTON 意图注册接收器(注册开启耳机线控监听, 请务必在设置接口监听之后再调用此方法,否则接口无效)
 * @param context
 */
public void open(Context context) {
	if(headSetListener==null){
		throw new IllegalStateException("please set headSetListener");
	}
	AudioManager audioManager = (AudioManager) context
			.getSystemService(Context.AUDIO_SERVICE);
	ComponentName name = new ComponentName(context.getPackageName(),
			MediaButtonReceiver.class.getName());
	audioManager.registerMediaButtonEventReceiver(name);
	Log.i("ksdinf", "open");
}
 
Example 5
Source File: VoIPBaseService.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if (Build.VERSION.SDK_INT >= 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 {
		VoIPController.setNativeBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
	}
	try {
		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);
		if(!USE_CONNECTION_SERVICE){
			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);
		}
		registerReceiver(receiver, filter);

		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(!USE_CONNECTION_SERVICE && 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();
		}

	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}
 
Example 6
Source File: VoIPBaseService.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	if (Build.VERSION.SDK_INT >= 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 {
		VoIPController.setNativeBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
	}
	try {
		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);
		if(!USE_CONNECTION_SERVICE){
			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);
		}
		registerReceiver(receiver, filter);

		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(!USE_CONNECTION_SERVICE && 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();
		}

	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}
 
Example 7
Source File: PlayerService.java    From IdealMedia with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();

	// initialize default output device
	if (!BASS.BASS_Init(-1, 44100, 0)) {
		return;
	}

	// look for plugins
	plugins = "";
       String path = getApplicationInfo().nativeLibraryDir;
	String[] list = new File(path).list();
	for (String s: list) {
		int plug = BASS.BASS_PluginLoad(path+"/"+s, 0);
		if (plug != 0) { // plugin loaded...
			plugins += s + "\n"; // add it to the list
		}
	}
	if (plugins.equals(""))
           plugins = "no plugins - visit the BASS webpage to get some\n";
	if(playerInterface != null) {
		playerInterface.onPluginsLoaded(plugins);
	}

       BASS.BASS_SetConfig(BASS.BASS_CONFIG_BUFFER, 1000);
       Log.w("BASS.BASS_CONFIG_BUFFER", "" + BASS.BASS_GetConfig(BASS.BASS_CONFIG_BUFFER));

	// Pending Intend
	Intent intent = new Intent(this, NavigationActivity.class);
	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
	pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

       //tracklist
       loadTracks();
       loadEqualizerValues();

       tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
       tm.listen(telephone, PhoneStateListener.LISTEN_CALL_STATE);

       myBroadcastReceiver = new ServiceBroadcastReceiver();
       IntentFilter intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
       intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");
       intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
       registerReceiver(myBroadcastReceiver, intentFilter);

       ComponentName rcvMedia = new ComponentName(getPackageName(), MediaControlReceiver.class.getName());
       mAudioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
       mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
       mAudioManager.registerMediaButtonEventReceiver(rcvMedia);

       // Use the remote control APIs (if available) to set the playback state
       if (Build.VERSION.SDK_INT >= 14 && remoteControlClient == null) {
           registerRemoteControl(rcvMedia);
       }
}
 
Example 8
Source File: MusicService.java    From Muzesto with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate() {
    if (D) Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = NotificationManagerCompat.from(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);
    mSongPlayCount = SongPlayCount.getInstance(this);
    mRecentStore = RecentStore.getInstance(this);


    mHandlerThread = new HandlerThread("MusicPlayerHandler",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();


    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());


    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        setUpMediaSession();

    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

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

    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 wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.setReferenceCounted(false);


    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(SHUTDOWN);

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

    scheduleDelayedShutdown();

    reloadQueueAfterPermissionCheck();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}
 
Example 9
Source File: ApolloService.java    From mobile-manager-tool with MIT License 4 votes vote down vote up
@SuppressLint({ "WorldWriteableFiles", "WorldReadableFiles" })
@Override
   public void onCreate() {
       super.onCreate();

       mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
       ComponentName rec = new ComponentName(getPackageName(),
               MediaButtonIntentReceiver.class.getName());
       mAudioManager.registerMediaButtonEventReceiver(rec);

       Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
       mediaButtonIntent.setComponent(rec);
       PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
               mediaButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);

       mRemoteControlClient = new RemoteControlClient(mediaPendingIntent);
       mAudioManager.registerRemoteControlClient(mRemoteControlClient);

       int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
               | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PLAY
               | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
               | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
               | RemoteControlClient.FLAG_KEY_MEDIA_STOP;
       mRemoteControlClient.setTransportControlFlags(flags);

       mPreferences = getSharedPreferences(APOLLO_PREFERENCES, MODE_WORLD_READABLE
               | MODE_WORLD_WRITEABLE);
       mCardId = MusicUtils.getCardId(this);

       registerExternalStorageListener();

       // Needs to be done in this thread, since otherwise
       // ApplicationContext.getPowerManager() crashes.
       mPlayer = new MultiPlayer();
       mPlayer.setHandler(mMediaplayerHandler);

       reloadQueue();
       notifyChange(QUEUE_CHANGED);
       notifyChange(META_CHANGED);

       IntentFilter commandFilter = new IntentFilter();
       commandFilter.addAction(SERVICECMD);
       commandFilter.addAction(TOGGLEPAUSE_ACTION);
       commandFilter.addAction(PAUSE_ACTION);
       commandFilter.addAction(NEXT_ACTION);
       commandFilter.addAction(PREVIOUS_ACTION);
       commandFilter.addAction(CYCLEREPEAT_ACTION);
       commandFilter.addAction(TOGGLESHUFFLE_ACTION);
       registerReceiver(mIntentReceiver, commandFilter);

       PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);

       mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());

       mWakeLock.setReferenceCounted(false);

       // If the service was idle, but got killed before it stopped itself, the
       // system will relaunch it. Make sure it gets stopped again in that
       // case.
       Message msg = mDelayedStopHandler.obtainMessage();
       mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
   }
 
Example 10
Source File: MediaPlaybackService.java    From coursera-android with MIT License 4 votes vote down vote up
@Override
    public void onCreate() {
        super.onCreate();

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        ComponentName rec = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mAudioManager.registerMediaButtonEventReceiver(rec);
        // TODO update to new constructor
//        mRemoteControlClient = new RemoteControlClient(rec);
//        mAudioManager.registerRemoteControlClient(mRemoteControlClient);
//
//        int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
//                | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
//                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY
//                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
//                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
//                | RemoteControlClient.FLAG_KEY_MEDIA_STOP;
//        mRemoteControlClient.setTransportControlFlags(flags);
        
        mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
        mCardId = MusicUtils.getCardId(this);
        
        registerExternalStorageListener();

        // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
        mPlayer = new MultiPlayer();
        mPlayer.setHandler(mMediaplayerHandler);

        reloadQueue();
        notifyChange(QUEUE_CHANGED);
        notifyChange(META_CHANGED);

        IntentFilter commandFilter = new IntentFilter();
        commandFilter.addAction(SERVICECMD);
        commandFilter.addAction(TOGGLEPAUSE_ACTION);
        commandFilter.addAction(PAUSE_ACTION);
        commandFilter.addAction(NEXT_ACTION);
        commandFilter.addAction(PREVIOUS_ACTION);
        registerReceiver(mIntentReceiver, commandFilter);
        
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
        mWakeLock.setReferenceCounted(false);

        // If the service was idle, but got killed before it stopped itself, the
        // system will relaunch it. Make sure it gets stopped again in that case.
        Message msg = mDelayedStopHandler.obtainMessage();
        mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
    }
 
Example 11
Source File: VoIPBaseService.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	try {
		AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (Build.VERSION.SDK_INT >= 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));
			TgVoip.setBufferSize(outFramesPerBuffer);
		} else {
			TgVoip.setBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
		}

		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);
		if(!USE_CONNECTION_SERVICE){
			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);
		}
		registerReceiver(receiver, filter);

		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(!USE_CONNECTION_SERVICE && 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();
		}
	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}
 
Example 12
Source File: ServicePlayer.java    From freemp with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // initialize default output device
    if (!BASS.BASS_Init(-1, 44100, 0)) {
        return;
    }

    // look for plugins
    plugins = "";
    String path = getApplicationInfo().nativeLibraryDir;
    String[] list = new File(path).list();
    for (String s : list) {
        int plug = BASS.BASS_PluginLoad(path + "/" + s, 0);
        if (plug != 0) { // plugin loaded...
            plugins += s + "\n"; // add it to the list
        }
    }
    if (plugins.equals("")) plugins = "no plugins - visit the BASS webpage to get some\n";
    if (activity != null) {
        activity.onPluginsLoaded(plugins);
    }
    BASS.BASS_SetConfig(BASS.BASS_CONFIG_BUFFER, 1000);
    Log.w("BASS.BASS_CONFIG_BUFFER", "" + BASS.BASS_GetConfig(BASS.BASS_CONFIG_BUFFER));
    //screen
    screenHeight = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt("screenHeight", 1000);
    screenWidth = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt("screenWidth", 800);

    // Pending Intend
    Intent intent = new Intent(this, ActPlayer.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

    //tracklist
    updateTrackList();

    tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    tm.listen(telephone, PhoneStateListener.LISTEN_CALL_STATE);
    myBroadcastReceiver = new MyBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");
    intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    registerReceiver(myBroadcastReceiver, intentFilter);


    mAudioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    ComponentName rcvMedia = new ComponentName(getPackageName(), RcvMediaControl.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(rcvMedia);

    // Use the remote control APIs (if available) to set the playback state
    if (android.os.Build.VERSION.SDK_INT >= 14 && remoteControlClient == null) {
        registerRemoteControl(rcvMedia);
    }
}
 
Example 13
Source File: PlayerService.java    From misound with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    mWorker = new Worker("Soundbar_palyer_service");
    mMediaplayerHandler = new PlayerHandler(mWorker.getLooper());
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    ComponentName rec = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(rec);

    mPreferences = getSharedPreferences("Music", MODE_PRIVATE | MODE_PRIVATE);
    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();

    // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
    mPlayer = new MultiPlayer();
    mPlayer.setHandler(mMediaplayerHandler);

    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);

    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(SERVICECMD);
    commandFilter.addAction(TOGGLEPAUSE_ACTION);
    commandFilter.addAction(PAUSE_ACTION);
    commandFilter.addAction(NEXT_ACTION);
    commandFilter.addAction(PREVIOUS_ACTION);
    commandFilter.addAction(STOP_ACTION);
    registerReceiver(mIntentReceiver, commandFilter);

    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    mWakeLock.setReferenceCounted(false);

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
 
Example 14
Source File: VoIPBaseService.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	if (BuildVars.LOGS_ENABLED) {
		FileLog.d("=============== VoIPService STARTING ===============");
	}
	try {
		AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (Build.VERSION.SDK_INT >= 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));
			TgVoip.setBufferSize(outFramesPerBuffer);
		} else {
			TgVoip.setBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2);
		}

		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);
		if(!USE_CONNECTION_SERVICE){
			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);
		}
		registerReceiver(receiver, filter);

		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(!USE_CONNECTION_SERVICE && 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();
		}
	} catch (Exception x) {
		if (BuildVars.LOGS_ENABLED) {
			FileLog.e("error initializing voip controller", x);
		}
		callFailed();
	}
}