I am trying to log the phone number whenever I get an incoming call using BroadcastReceiver
. However, I do not get any log
when I dial to my number. This is the code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abc.broadcast_phone" >
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<receiver android:name=".MyPhoneReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("tuet");
sendBroadcast(intent);
}
}
MyPhoneReceiver.java
public class MyPhoneReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null)
{
String state = extras.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String phoneNumber = extras
.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.e("DEBUG", phoneNumber);
}
}
}
}
I am compiling using SDK 23 and target is also Marshmallow, should I be using run time permission in this case? Or am I missing something?
EDIT-1
Seems like the problem is only associated with Marshmallow onwards, when I downgraded the target sdk version, this is working fine : targetSdkVersion 22
.
So, how to tweak this to work in SDK23+ onwards?