Я хочу получить входящий номер всякий раз, когда кому-либо позвонят, но он становится пустым даже после использования. PhoneStateListener and BroadCastReceiver
.
Во-первых, проясните мои сомнения, какой из них лучше всего подходит и почему мы используемоба PhoneStateListener and BroadCastReceiver
.
Manifest File.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mytraining.com.callrecord">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".PhoneReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
</application>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}}
BroadcastReceiver.java
public class PhoneReceiver extends BroadcastReceiver {
private final String TAG = getClass().getName();
private static String number = null;
@Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.d(TAG, intent.getAction() + ", EXTRA_STATE: " + state);
// on ringing get incoming number
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "EXTRA_INCOMING_NUMBER: " + number);
}
}
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.d(TAG, intent.getAction() + ", EXTRA_PHONE_NUMBER: " + number);
}
}}