Example usage for android.telephony TelephonyManager listen

List of usage examples for android.telephony TelephonyManager listen

Introduction

In this page you can find the example usage for android.telephony TelephonyManager listen.

Prototype

public void listen(PhoneStateListener listener, int events) 

Source Link

Document

Registers a listener object to receive notification of changes in specified telephony states.

Usage

From source file:org.chirpradio.mobile.PlaybackService.java

private void setupTelephonyHooks() {
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

    phoneStateListener = new PhoneStateListener() {

        @Override/*from w  w w.j  a  v a  2 s .c  om*/
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_OFFHOOK:
            case TelephonyManager.CALL_STATE_RINGING:
                if (isPlaying) {
                    Debug.log(this, "call began, stopping...");
                    stop();
                    isInCall = true;
                }
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                if (isInCall) {
                    isInCall = false;
                    Debug.log(this, "call ended; resuming...");
                    start();
                }
                break;
            }
        }
    };

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}

From source file:za.co.neilson.alarm.alert.AlarmAlertActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    window.addFlags(/*w ww .ja v  a2s .co  m*/
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

    setContentView(R.layout.alarm_alert);

    Bundle bundle = this.getIntent().getExtras();
    alarm = (Alarm) bundle.getSerializable("alarm");

    sendNotification(this, alarm.getAlarmName(), alarm);

    this.setTitle(alarm.getAlarmName());

    switch (alarm.getDifficulty()) {
    case SUPEREASY:
        mathProblem = new MathProblem(1);
        break;
    case EASY:
        mathProblem = new MathProblem(3);
        break;
    case MEDIUM:
        mathProblem = new MathProblem(4);
        break;
    case HARD:
        mathProblem = new MathProblem(5);
        break;
    }

    answerString = String.valueOf(mathProblem.getAnswer());
    if (answerString.endsWith(".0")) {
        answerString = answerString.substring(0, answerString.length() - 2);
    }

    problemView = (TextView) findViewById(R.id.textView1);
    problemView.setText(mathProblem.toString());

    answerView = (TextView) findViewById(R.id.textView2);
    answerView.setText("= ?");

    ((Button) findViewById(R.id.Button0)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button1)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button2)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button3)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button4)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button5)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button6)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button7)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button8)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button9)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button_clear)).setOnClickListener(this);
    final AlarmAlertActivity foo = this;
    ((Button) findViewById(R.id.Button_alarm_off)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            alarmActive = false; //Toast.makeText(getApplicationContext(),"off",Toast.LENGTH_SHORT).show();
            foo.finish();
        }
    });
    ((Button) findViewById(R.id.Button_decimal)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button_minus)).setOnClickListener(this);

    TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                Log.d(getClass().getSimpleName(), "Incoming call: " + incomingNumber);
                try {
                    mediaPlayer.pause();
                } catch (IllegalStateException e) {

                }
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                Log.d(getClass().getSimpleName(), "Call State Idle");
                try {
                    mediaPlayer.start();
                } catch (IllegalStateException e) {

                }
                break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    // Toast.makeText(this, answerString, Toast.LENGTH_LONG).show();

    startAlarm();

}

From source file:org.metawatch.manager.Monitors.java

public static void start(Context context, TelephonyManager telephonyManager) {
    // start weather updater

    if (Preferences.logging)
        Log.d(MetaWatch.TAG, "Monitors.start()");

    createBatteryLevelReciever(context);
    createWifiReceiver(context);//  www . j a  v a 2 s .  c  om

    if (Preferences.weatherGeolocation) {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Initialising Geolocation");

        try {
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            locationProvider = LocationManager.NETWORK_PROVIDER;

            networkLocationListener = new NetworkLocationListener(context);

            locationManager.requestLocationUpdates(locationProvider, 30 * 60 * 1000, 500,
                    networkLocationListener);

            RefreshLocation();
        } catch (IllegalArgumentException e) {
            if (Preferences.logging)
                Log.d(MetaWatch.TAG, "Failed to initialise Geolocation " + e.getMessage());
        }
    } else {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Geolocation disabled");
    }

    CallStateListener phoneListener = new CallStateListener(context);

    telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    int phoneEvents = PhoneStateListener.LISTEN_CALL_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
            | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE;
    telephonyManager.listen(phoneListener, phoneEvents);

    if (Utils.isGmailAccessSupported(context)) {
        gmailMonitor = new GmailMonitor(context);
        gmailMonitor.startMonitor();
    }

    try {
        contentObserverMessages = new ContentObserverMessages(context);
        Uri uri = Uri.parse("content://mms-sms/conversations/");
        contentResolverMessages = context.getContentResolver();
        contentResolverMessages.registerContentObserver(uri, true, contentObserverMessages);
    } catch (Exception x) {
    }

    try {
        contentObserverCalls = new ContentObserverCalls(context);
        //Uri uri = Uri.parse("content://mms-sms/conversations/");
        contentResolverCalls = context.getContentResolver();
        contentResolverCalls.registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI, true,
                contentObserverCalls);
    } catch (Exception x) {
    }

    try {
        contentObserverAppointments = new ContentObserverAppointments(context);
        Uri uri = Uri.parse("content://com.android.calendar/calendars/");
        contentResolverAppointments = context.getContentResolver();
        contentResolverAppointments.registerContentObserver(uri, true, contentObserverAppointments);
    } catch (Exception x) {
    }

    // temporary one time update
    updateWeatherData(context);

    startAlarmTicker(context);
}

From source file:org.tomahawk.tomahawk_android.services.PlaybackService.java

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

    EventBus.getDefault().unregister(this);

    pause(true);/*from  w w  w.jav a2 s  . com*/
    releaseAllPlayers();
    if (mWakeLock.isHeld()) {
        mWakeLock.release();
    }
    mWakeLock = null;
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(mPhoneCallListener, PhoneStateListener.LISTEN_NONE);
    mPhoneCallListener = null;
    mKillTimerHandler.removeCallbacksAndMessages(null);
    mKillTimerHandler = null;

    Log.d(TAG, "PlaybackService has been destroyed");
}

From source file:org.tomahawk.tomahawk_android.services.PlaybackService.java

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

    EventBus.getDefault().register(this);

    mMediaPlayers.add(VLCMediaPlayer.get());
    mMediaPlayers.add(DeezerMediaPlayer.get());
    mMediaPlayers.add(SpotifyMediaPlayer.get());
    mMediaPlayers.add(RdioMediaPlayer.get());

    startService(new Intent(this, MicroService.class));

    ServiceConnection connection = new ServiceConnection() {
        @Override//from   ww  w . j a v a2s .  co m
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        bindService(new Intent(this, RemoteControllerService.class), connection, Context.BIND_AUTO_CREATE);
    }

    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Initialize PhoneCallListener
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(mPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);

    // Initialize WakeLock
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    mMediaButtonReceiverComponent = new ComponentName(this, MediaButtonReceiver.class);
    mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);

    // Initialize killtime handler (watchdog style)
    mKillTimerHandler.removeCallbacksAndMessages(null);
    Message msg = mKillTimerHandler.obtainMessage();
    mKillTimerHandler.sendMessageDelayed(msg, DELAY_TO_KILL);

    mPlaylist = Playlist.fromEmptyList(TomahawkMainActivity.getLifetimeUniqueStringId(), false, "");
    mQueue = Playlist.fromEmptyList(TomahawkMainActivity.getLifetimeUniqueStringId(), false, "");
    Log.d(TAG, "PlaybackService has been created");
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);

    unregisterReceiver(interactiveStateReceiver);
    unregisterReceiver(connectivityChangedReceiver);

    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
        phone_state = false;//w w  w  . j a  v  a2 s . c  om
    }
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

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

    // Check if permissions were revoked
    checkPermissions();//  ww  w .j  ava  2  s. c  o m

    // Listen for preference changes
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Listen for interactive state changes
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(interactiveStateReceiver, ifInteractive);

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);

    if (Util.hasPhoneStatePermission(this)) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(phoneStateListener,
                PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | PhoneStateListener.LISTEN_SERVICE_STATE);
        phone_state = true;
    }
}

From source file:org.mariotaku.harmony.MusicPlaybackService.java

@Override
public void onDestroy() {

    // Check that we're not being destroyed while something is still
    // playing./*from   w  w w  . ja v  a2 s  .  c  om*/
    if (isPlaying()) {
        Log.e(LOGTAG_SERVICE, "Service being destroyed while still playing.");
    }

    mPlayer.release();
    mPlayer = null;

    mAudioManager.abandonAudioFocus(mAudioFocusListener);

    final TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);

    // make sure there aren't any other messages coming
    mDelayedStopHandler.removeCallbacksAndMessages(null);
    mMediaplayerHandler.removeCallbacksAndMessages(null);

    mTrackInfo = null;

    unregisterReceiver(mIntentReceiver);
    unregisterReceiver(mA2dpReceiver);
    unregisterReceiver(mExternalAudioDeviceStatusReceiver);
    if (mUnmountReceiver != null) {
        unregisterReceiver(mUnmountReceiver);
        mUnmountReceiver = null;
    }
    mWakeLock.release();
    mNotificationManager.cancelAll();
    super.onDestroy();
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

@Override
public void onDestroy() {
    Log.i(TAG, "Destroy");

    commandLooper.quit();// w  ww.  ja  va 2 s  .  c  o  m
    logLooper.quit();
    statsLooper.quit();

    unregisterReceiver(interactiveStateReceiver);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        unregisterReceiver(powerSaveReceiver);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
        unregisterReceiver(userReceiver);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        unregisterReceiver(idleStateReceiver);
    unregisterReceiver(connectivityChangedReceiver);
    unregisterReceiver(packageAddedReceiver);

    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            phone_state = false;
        }
    }

    if (subscriptionsChangedListener != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        SubscriptionManager sm = SubscriptionManager.from(this);
        sm.removeOnSubscriptionsChangedListener(
                (SubscriptionManager.OnSubscriptionsChangedListener) subscriptionsChangedListener);
        subscriptionsChangedListener = null;
    }

    try {
        if (vpn != null) {
            stopNative(vpn, true, true);
            stopVPN(vpn);
            vpn = null;
            unprepare();
        }
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    jni_done();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);

    super.onDestroy();
}