Send sms permission doesn't work - android

I want to send a simple message and i have <uses-permission android:name="android.permission.SEND_SMS"/> in my manifest, but I always get: java.lang.SecurityException: Sending SMS message: uid 10064 does not have android.permission.SEND_SMS.
I checked this answer, but it still doesn't work.
this is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.roa.sendsms" >
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
and this is my code:
package com.roa.sendsms;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.SmsManager;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button sendButton = (Button)findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendSms(phoneNumber, "you get message from roish app!!");
}
});
}
private void sendSms(String phoneNumber, String message){
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
thank to all.

Try to use something like this. Not tested, but should work fine. Drop a note when you see some problem here.
This is just to show how permission granting in Android M works. Please extend it by functionalities mentioned on Android tutorial site about permissions.
You will need add ActivityCompat.shouldShowRequestPermissionRationale check to match best practices. I can extend this answer but I think it's not necessary. Just make sure you are granting permissions in runtime (or use targetSdkVersion lower then 23 - this is however not recommended)
private static final int PERMISSION_SEND_SMS = 123;
private void requestSmsPermission() {
// check permission is given
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
// request permission (see result in onRequestPermissionsResult() method)
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.SEND_SMS},
PERMISSION_SEND_SMS);
} else {
// permission already granted run sms send
sendSms(phone, message);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
sendSms(phone, message);
} else {
// permission denied
}
return;
}
}
}
private void sendSms(String phoneNumber, String message){
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}

All you need to do is,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.roa.sendsms"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.homesafe.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try to run into the mobile instead checking it to the emulator. Just because emulator does not have the sim card as our mobiles have, so.

i had same problem you need to get runtime permission on setting>app>"your app" >enable sms permission

If you message is too long using smsManager.sendTextMessage(.. will fail quietly.
You need to use smsManager.sendMultipartTextMessage(...
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> messageList = smsManager.divideMessage(message.toString());
smsManager.sendMultipartTextMessage(phoneNumber, null, messageList, null, null);

You may try this way:
private void sendSms(String phoneNumber, String message) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse( "sms:" + phoneNumber ) );
intent.putExtra( "sms_body", message );
startActivity(intent);
}

I tried this in Huawei Android 8, besides adding permission READ_PHONE_STATE in manifest, the phone needs to allow to "access phone ID" to the app. Then it works.

Related

Checking if a Broadcast Receiver is Working

I am working on an app that will use a BroadcastReceiver to pick up certain SMS messages that meet certain criteria. It's a long way short of finished, mainly because it seems that the BroadcastReceiver isn't working. I've tried to use a toast to check if it's working but I get no result. So either:
The BroadcastReceiver is not working
My method of testing is wrong
Or both
The AndroidManifest.xml file is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.alert6">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Alert6">
<activity
android:name=".SendResponseActivity"
android:parentActivityName=".ReceiveAlertActivity">
</activity>
<activity
android:name=".ReceiveAlertActivity"
android:parentActivityName=".MainActivity">
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
And this is the SmsBroadcastReceiver java file
package com.example.alert6;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"SMS Is Being Received",Toast.LENGTH_LONG).show();
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
String smsSender = "";
String smsBody = "";
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.getOriginatingAddress();
smsBody = smsMessage.getMessageBody();
}
if (smsSender.equals("+420775367297")) {
if (smsBody.contains("Test")) {
// I haven't done this bit yet
}
}
}
}
}
When I send a SMS to the test device I would expect a toast message saying "SMS Is Being Received". Instead the app disappears from the screen and my default SMS app appears instead. What am I doing wrong?
Since Android API 23 you need set permission not only in manifest class, but also set permisson manually. You should set it in app's settings, or you should make permission reqeust from your code. This is what you need add in your main activity's file:
// constant for request code
private final int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10; // any number which you want
//function for permission request
#RequiresApi(api = Build.VERSION_CODES.M)
public void checkPermission() {
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED)) {
requestPermissions(new String[]{Manifest.permission.RECEIVE_SMS}, MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
}
}
Also you need call this function somewhere. For example you can make it in onCreate().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission();
}
//do something else
}
After a huge amount of fiddling and testing, I came to the conclusion that the broadcast receiver is not working. Probably due to Android's limitations on "dangerous" permissions. I don't think this thread has any life left in it, but I will continue to try to persuade my Android app to work with the necessary permissions.

Android Sms Broadcast Receiver not firing despite priority

I have read many similar questions that usually results in an answer about priority. The reason I don't think this is true in my case is that other SMS readers on my phone (like automation apps) receive the broadcasts just fine. I would like to post the process of what I'm doing currently and make triple sure that I'm not doing something wrong in my code that would cause this to fail. Thanks for any tips you can give!
Note: I've tried with the highest integer priority, priority 99, 100, 0, or none set at all. They all don't work.
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hennessylabs.appname" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.hennessylabs.drivercompanion.ProcessTextMessage" android:exported="true">
<intent-filter android:priority="999" android:permission="android.permission.BROADCAST_SMS">
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
</manifest>
BroadcastReceiver:
package com.hennessylabs.appname;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
/**
* Created by kyleC on 11/15/2015.
*/
public class ProcessTextMessage extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
final SmsManager sms = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Entered onReceive", Toast.LENGTH_LONG).show();
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
Expected Result:
The expected result is that when an SMS arrives, the screen would first show a Toast that it entered the OnReceive method. Then it would log and Toast the contents of the SMS.
Actual Result:
Nothing from the expected result happens. In fact even while connected to USB and in debug mode it never seems to enter that class at all. So maybe I have my manifest set up wrong?
Provided everything else is correct, it looks like you're just missing the RECEIVE_SMS permission.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
You are missing some things from the manifest declaration of your receiver. You must declare exported=true and you must require the BROADCAST_SMS permission. See working example:
<receiver android:name=".sms.IncomingSmsReceiver" android:exported="true">
<intent-filter android:priority="999" android:permission="android.permission.BROADCAST_SMS">
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
So what is the version of the device your app is running on?
Begins in Android 4.4, only the default sms app can receive the SMS_DELIVER_ACTION broadcast.
more information: http://android-developers.blogspot.sg/2013/10/getting-your-sms-apps-ready-for-kitkat.html

getIntent().getData() == null for unity app

so Im running a java plugin that extends UnityPlayerActivity. Im successfully overwriting the onCreate function. Only problem is when I try to get the intent data coming in, its null. The data Im looking for is the url that Triggered the Intent.
package com.company.androidlink;
import java.net.URL;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.unity3d.player.*;
public class Main extends UnityPlayerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
uri = intent.getData();
url = new URL(uri.getScheme(), uri.getHost(), uri.getPath());
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company.androidlink"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I developed a plugin some months ago to send a text to a Unity3D app. The method, which is in the root activity (equivalent to your "Main") is the following:
public static String getExtraText() {
String extraText = "";
// Store extra parameter for later.
Intent intent = UnityPlayer.currentActivity.getIntent();
if (intent != null) {
String action = intent.getAction();
String type = intent.getType();
if (action.equals(Intent.ACTION_VIEW) && type != null) {
if (type.equals("text/plain")) {
extraText = intent.getStringExtra(Intent.EXTRA_TEXT);
DebugBridge.log_d("Extra Text: " + extraText);
} else {
DebugBridge.toast("Unknown MIME type");
}
}
}
return extraText;
}
I did not get the text at startup, just invoke the "getExtraText" from Unity app when needed (at Start usually).
This is the way I send data from another android native test app to unity:
boolean sendMessageToApp(String message, String appName) {
ComponentName name = findNativeApp(appName);
if (name != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setComponent(name);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, message);
startActivity(intent);
return true;
}
return false;
}

Receiving the Broadcast

I want to make a application that gets the incoming calling number if the call is from a specific number then do some stuff . I want to get the incoming calling number even when the application is not running .. I am using the BraodcastReceiver to get the incoming number .
I have two java class one which extends he activity and the other extends the BraodcastReceiver for getting the incoming calling number .
Main class which extends activity :
package digicare.ringmanager;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class Main_Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_layout, menu);
return true;
}
}
it is pretty simple and the Number checker class which extends the BroadcastReceiver :
package digicare.ringmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
public class number_checker extends BroadcastReceiver {
private int ringer_mode ;
private String AM_str;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
AudioManager AM =(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
Log.w("start", "starting the Main_Activity");
AM_str=String.valueOf(ringer_mode);
Log.w("Ringer_mode at start", AM_str);
//setting the ringer mode on number match
try {
Bundle extras=intent.getExtras();
if (extras !=null){
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.w("state at start",state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
String phonenumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
//AM.setRingerMode(1);
ringer_mode =AM.getRingerMode();
AM_str=String.valueOf(ringer_mode);
Log.w("Ringer_mode at ringing", AM_str);
Log.w("Number", phonenumber);
if (phonenumber.equals("1234")){
Log.w("yahoo", "Number matched");
if (ringer_mode==AudioManager.RINGER_MODE_SILENT || ringer_mode==AudioManager.RINGER_MODE_VIBRATE ){
AM.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.w("Phone number is matched .!", "Now , ringer mode is normal");
int now_nor =AM.getRingerMode();
String now_nor_str=String.valueOf(now_nor);
Log.w("ring_mode at num matched",now_nor_str);
}
}
}
if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK ) || state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
int now_nor =AM.getRingerMode();
String now_nor_str=String.valueOf(now_nor);
Log.w("ring_mode at offHock",now_nor_str);
if (ringer_mode==AudioManager.RINGER_MODE_NORMAL){
AM.setRingerMode(AudioManager.RINGER_MODE_NORMAL );
Log.w("Normal", "");
}else if (ringer_mode==AudioManager.RINGER_MODE_SILENT ){
AM.setRingerMode(AudioManager.RINGER_MODE_SILENT );
Log.w("silent", "");
}else if (ringer_mode==AudioManager.RINGER_MODE_VIBRATE ){
AM.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.w("vibrat", "");
}
// Log.w("Again", "Now the Ringer mode is get back ");
int now =AM.getRingerMode();
String now_str=String.valueOf(now);
Log.w("ring_mode at end ",now_str);
}
}
} catch (Exception e) {
// TODO: handle exception
Log.w("MY_DEBUG_TAG", e);
}
}
}
And the AndroidManifist.xml is this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="digicare.ringmanager"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="digicare.ringmanager.Main_Activity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="number_checker" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
</application>
</manifest>
but this not working this cannot get the incoming calling number .
wot could i do ???? have to call the number_checker class for register the Braodcast ???
please help i am a new android developer
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.
Note: If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.
also check this link :
http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
NEW Update:
check this link http://androidexample.com/Incomming_Phone_Call_Broadcast_Receiver__-_Android_Example/index.php?view=article_discription&aid=61&aaid=86
Update 2
put . before the receiver name. like this <receiver android:name=".number_checker" >

Retrieve incoming call's phone number in Android

I would like to retrieve the incoming call's phonenumber and do something with it like the do
in http://blog.whitepages.com/2009/02/27/caller-id-by-whitepages-a-new-android-app-that-puts-telemarketers-on-alert/
Could you please help me because I can't find any information about this.
Where do i start and how do i get hold of the phonenumber?
Ok so currently my code looks like below. When I place the call the CustomBroadcastReceiver catches it and the log message is printed out. I can retrieve the telephone number from the bundle. But! I can't get hte CustomPhoneStateListener to work. As you can see I have registered my customPhoneState listener to the receiver but the log message never get's printed out from the CustomPhoneStateListener class. What am I my missing here?
Is my thinking correct?
<receiver android:name=".CustomBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="5" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListener";
public void onCallStateChange(int state, String incomingNumber){
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
Log.v(TAG, incomingNumber);
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "RINGING");
break;
}
}
public class CustomBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phoneNr= bundle.getString("incoming_number");
Log.v(TAG, "phoneNr: "+phoneNr);
}
Use PhoneStateListener. It has an onCallStateChanged handler; one of the supplied arguments you'll get is a String containing the incoming phone number.
Your overridden method in CustomPhoneStateListener should be called onCallStateChanged() (and not onCallStateChange()).
This would have been spotted by the Java compiler if you would have had the #Override annotation, like you have for onReceive().
The above answers are out-od-dated now. There are valid for Android 7 and lower.
For android 9 and higher you have to add another permission in the Androidmanifest.xml with the permission
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
without the phone number will be null. For Android 8 I am not sure.
PhoneStateReciever.java
package com.incomingcalls;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class PhoneStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.e("Incoming Number", "Number is ," + incomingNumber);
Log.e("State", "State is ," + state);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
Toast.makeText(context,"Incoming Call State",Toast.LENGTH_SHORT).show();
Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
AnroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.incomingcalls">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>

Categories

Resources