I am trying to find out whether a incoming call from favourites contacts in Android.
So far, my code is:
public class PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
if (state == TelephonyManager.CALL_STATE_RINGING) {
if (ContactHelper.fromFavourites(context, incomingNumber)) {
//do stuff
}
}
};
And my ContactHelper is like this:
public static boolean fromFavourites(Context context, String phoneNumber) {
final String[] projection = new String[] {ContactsContract.PhoneLookup._ID};
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); //use this to look up a phone number
Cursor cursor = context.getContentResolver().query(lookupUri, projection, "starred=?", new String[] { "1" }, null);
if (cursor != null && cursor.getCount() != 0) {
System.out.println("OUTPUT: "+cursor0.getCount());
return true;
} else return false;
}
I have tried this solution but it only gives me all favourites contacts. I am trying to use PhoneLookup because from the Android doc, it says
Columns from the Contacts table are also available through a join.
So I think I can query a join between PhoneLookUp and Contacts table but seems like the Content Providers can't do a join. I intend to write a raw SQLite script for this but I don't know how to join the PhoneLookUp and Contacts table, can't find their foreign key :( Thanks for all the helps
public static boolean fromFavourites(Context context, String phoneNumber) {
final String[] projection = new String[] {ContactsContract.PhoneLookup.STARRED};
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); //use this to look up a phone number
Cursor cursor = context.getContentResolver().query(lookupUri, projection,
ContactsContract.PhoneLookup.NUMBER + "=?",
new String[] { phoneNumber}, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.PhoneLookup.STARRED)) == 1) {
System.out.println("OUTPUT: " + cursor.getInt(0) );
return true;
}
cursor.moveToNext();
}
}
return false;
}
your first link is okay to get all favorite contacts. now to determine whether the incoming number is from favorite you have to detect a incoming call. So use a PhoneStateListener to detect the inocming call. When there is a incoming call detection then simply check for the favorite
To detect an incoming call
public class CustomPhoneStateListener extends PhoneStateListener {
public void onCallStateChange(int state, String number){
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
//call from number. check whether it is favorite or not
break;
}
}
also use following permission
< uses-permission android:name="android.permission.READ_PHONE_STATE" />
Related
I use media Store to get All the files from the Storage but my code didn't work . help me to solve issue. I tried all the tricks from the internet but also after that i am not able to solve this..
enter code here
public List<Song> getAllAudioFromDevice(final Context context) {
final ArrayList<Song> tempAudioList = new ArrayList<Song>();
File temp= (File)Environment.getExternalStorageDirectory();
String selection=MediaStore.Audio.Media.IS_MUSIC+"!=0";
Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
Log.d("file",temp.toString());
String[] projection = {MediaStore.Audio.Media._ID,
// MediaStore.Audio.Media.TITLE,
// MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST
// MediaStore.Audio.Media.ALBUM_ID
};
Cursor c = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, selection,null,null,null);
if (c != null) {
do {
Song audioModel = new Song();
int path =(c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
int name =c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
int album =(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
audioModel.setaName(c.getString(name));
Log.e("Uri",(c.getString(name)));
audioModel.setaAlbum(c.getString(album));
audioModel.setaPath(c.getString((path)));
Log.e("Name :", audioModel.toString());
tempAudioList.add(audioModel);
}while (c.moveToNext());
c.close();
}
Log.e("N", Integer.toString(tempAudioList.size()) );
return tempAudioList; }
I am using Google auth via firebase and am logging the users in successfully. I also have retrieved the list of contacts from the phonebook (device) and displaying it on a listview in a fragment in my app. But now I wish to show the users amongst my contacts who have my app installed, so that when clicked on they will go to the private chat with them, the other contacts, when clicked on will enable them to send an app invite. In a nutshell: I want to view the list of contacts who have the app installed on their device.
I was able to achieve this in three straightforward steps.
Get a list of your phone contacts
Get a list of all the phone numbers on Firestore
Compare the two lists and return common elements.
In order to use my approach, you need to have a collection on Firestore that has the phone number of all your users as documents just like the image below:
Here are the steps:
Step 1: I got a list of all the user's contacts by using ContentResolver. You can use the method below to retrieve this list provided you have the READ_CONTACTS permission granted.
public ArrayList<String> getContacts(ContentResolver cr) {
// list to be returned
ArrayList<String> numbers = new ArrayList<>();
// cursor
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
numbers.add(formatRightWay(phoneNo));
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
return numbers;
}
Step 2: I got a list of all the phone numbers on Firestore by fetching the document IDs of the user collection. Here's a quick implementation:
firestore.collection("users").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
// this is the list you need
Log.d(TAG, list.toString());
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Step 3: Write a method that compares the two lists and returns similar elements.
public static ArrayList<String> shuffleBothLists(ArrayList<String> phoneContacts, List<String> firebaseContacts) {
ArrayList<String> result = new ArrayList<>();
for(String s: firebaseContacts) {
if(phoneContacts.contains(s) && !result.contains(s)) {
result.add(s);
}
}
return result;
}
The list returned by the method above are your contacts that have the app installed.
Cheers!
It is not possible to list the contacts directly. You need to create one node for users in firebase database to store users details after registration and then you can retrieve those user details.
I am getting you in means that you are using firebase. Now you want to upload all contacts to your server in firebase databse by your app if installed in one's device.
Try below code:
public class YourActivity extends AppCompatActivity {
ProgressDialog dialog;
DatabaseReference yourReference;//your database reference
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yourReference = FirebaseDatabase.getInstance().getReference().child("users");
setContentView(R.layout.activity_your);
dialog = new ProgressDialog(this);
dialog.setMessage("Uploading contacts...");
// Query for contacts through content resolver. You will get a cursor.
Cursor contacts = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
},
null,
null,
null
);
// If you have a list as your data, firebase facilitates you to upload that easily by a single HashMap object. Create a HashMap object.
HashMap<String,Object> map = new HashMap<>();
// Loop contacts cursor with map to put all contacts in map. I used contact name as key and number as its value (simple and pretty way).
if(contacts!=null) {
while(contacts.moveToNext()){
map.put(
contacts.getString(contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)),
contacts.getString(contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
);
}
contacts.close();
}
dialog.show();
//write map to firebase database reference...
yourReference.updateChildren(map)
//this onSuccessListener is optional. You can terminate above line of code by ";" (semicolon).
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
Toast.makeText(YourActivity.this, "Contacts uploaded suffessfully!", Toast.LENGTH_SHORT).show();
}
})
//this onFailureListener is also optional.
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
dialog.dismiss();
Log.w("MKN","Error: "+e.getMessage());
Toast.makeText(YourActivity.this, "Contacts upload failed.", Toast.LENGTH_SHORT).show();
}
});
}
}
You will need to provide READ_CONTACTS permission to query Contacts table.
Also in firebase rules, value for "write" key must be "true" to write to the database.
First retrieve the contact list ..
'ContentResolver cr = getContext().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
//to get the contact names
HashMap<String, String> map = new HashMap<>();
String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if( email != null ){
map.put("name", name);
map.put("email", email);
getContactList.add(map);
}
}
cur1.close();
}
}'
After this you can maintain a firebase database table that can store authenticated user's information, you can sync your contacts with the list you fetch from firebase user's database.
'mapChat = new HashMap<>();
Log.d("Debug", clist.toString());
userReference1 = FirebaseDatabase.getInstance().getReference().child("Users");
userReference1.keepSynced(true);
userReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (int x = 0; x < clist.size(); x++) {
//Log.d("Debug" ,list.get(x).get("email").toString());
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
if (dsp.hasChild("email")) {
// Log.d("Debug" , "setnewuser " + dsp.child("email").getValue().toString());
if (dsp.child("email").getValue().toString().equals(clist.get(x).get("email").toString())) {
Log.d("Debug", "contact updated");
String uid = dsp.getKey().toString();
reference1 = FirebaseDatabase.getInstance().getReference().child("Users").child(id).child("contacts").child(uid);
mapChat.put("name", clist.get(x).get("name"));
mapChat.put("email", clist.get(x).get("email"));
mapChat.put("chats", "false");
reference1.setValue(mapChat);
}
}
}
}
reference1.onDisconnect();
contactIdInterface1.contactUpdated();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});'
Enable and Implement Phone number sign in method in firebase, so u can retrieve the contacts from firebase and compare it will local contact list after that its easy to implement ur logic
Hi I'm trying to get names and phone numbers from contact
this is the class which extends BroadcastReceiver
public class TextMessageReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent)
{
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
//MainActivity.
String num = getcont( MainActivity.,msg.getOriginatingAddress());
MainActivity.updateMessageBox("Message de la part: "+msg.getOriginatingAddress()+"\n"+
"Qui vous dit: "+msg.getMessageBody()+"\n");
}
}
In the Onrecieve methode I get the sms and the the one who send it,but I'd like to get the name not the number after some researche I found this way:
public static String getcont (Context context ,String num)
{
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String numbr = null;
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String number = people.getString(numberFieldColumnIndex);
if (number.equals(num)) {
numbr = contact;
}
}
people.close();
return numbr;
}
I have an Activity called MainActivity I try to call the method getcont()
String num = getcont( MainActivity ,msg.getOriginatingAddress());
but it show me this error
MainActivity cannot be resolved to a variable
theres an other way to call getContentResolver().query() and thnx for helping me
How about using an intent to navigate to MainActivity?
if I fully understood your requiremnet ...
Instead of doing
String num = getcont( MainActivity ,msg.getOriginatingAddress());
why not do something like this?
Intent ii=new Intent(MainActivity.this, newclass.class);
ii.putExtra("name", s);
startActivity(ii);
In my application i am using "apn" for GPRS connection display. I code a spinner in which i get the Telenor GPRS, Telenor MMS and Telenor WAP.
**I want to add Wi-Fi option in this spinner. and when i select Wi-Fi option device start sensing Wi-Fi.
Q: How can i add option of Wi-Fi in my spinner??
**
This is my Code
Spinner GPRS;
String [] name_of_GPRS__available;
int [] apn_id; public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configuration);
EnumerateAPNs();
/* this is a android enviroment in which you can develop an android application in which you
* share all your basic necessities of thrkife bghhr4y2ghrrr*/
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GPRS = (Spinner)findViewById(R.id.GPRS);
ArrayAdapter<?> spinner_array = new ArrayAdapter<Object>(this,android.R.layout.simple_dropdown_item_1line,name_of_GPRS__available);
spinner_array.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = prefs.edit();
prefsEditor.putString("Object", name_of_GPRS__available.toString());
prefsEditor.commit();
GPRS.setAdapter(spinner_array);
//GPRS.setOnItemSelectedListener(MyOnItemSelectedListener());
GPRS.setOnItemSelectedListener(new MyOnItemSelectedListener());`
GPRS.setAdapter(spinner_array);
//GPRS.setOnItemSelectedListener(MyOnItemSelectedListener());
GPRS.setOnItemSelectedListener(new MyOnItemSelectedListener());
public void onItemSelected(AdapterView<?> parent, View view,
final int position, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(position)
SetDefaultAPN(apn_id[position]);
Toast.makeText(parent.getContext(), "ETracking System Selects " +
parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public boolean SetDefaultAPN(int id)
{
boolean res = false;
ContentResolver resolver = Configuration.this.getContentResolver();
ContentValues values = new ContentValues();
values.put("apn_id", id);
try
{
resolver.update(Uri.parse("content://telephony/carriers/preferapn"), values, null, null);
Cursor c = resolver.query(
Uri.parse("content://telephony/carriers/preferapn"),
null,
"_id="+id,
null,
null);
if(c != null)
{
res = true;
c.close();
}
}
catch (SQLException e)
{
//Log.d("TAG", e.getMessage());
}
return res;
}
/*
* Enumerate all APN data
*/
private void EnumerateAPNs()
{
Cursor c = this.getContentResolver().query(
Uri.parse("content://telephony/carriers/current"), null, null, null, null);
if (c != null)
{
//String s = "All APNs:\n";
//Log.d("TAG", s);
try
{
printAllData(c); //Print the entire result set
}
catch(SQLException e)
{
Toast.makeText(Configuration.this, "No Network Connection Available", Toast.LENGTH_LONG).show();
}
c.close();
}
}
/*
* Print all data records associated with Cursor c.
* Return a string that contains all record data.
* For some weird reason, Android SDK Log class cannot print very long string message.
* Thus we have to log record-by-record.
*/
private void printAllData(Cursor c)
{
//if(c == null) return null;
if(c.moveToFirst())
{
name_of_GPRS__available = new String[c.getCount()];
apn_id = new int [c.getCount()];
int i= 0;
do{
name_of_GPRS__available [i]= c.getString(c.getColumnIndex("name"));
apn_id[i]=c.getInt(c.getColumnIndex("_id"));
//Log.d("TAG",name[i]);
i++;
}while(c.moveToNext());
//Log.d("TAG","End Of Records");
//name_of_GPRS_available [1]=" GPRS";
}
}
Kindly guide me. How can i do it. I'll be very thankful to you
I assume that this is for a Gingerbread Device as Setting the Default APN was removed in ICS (4.0 - API 14), deprecated.
Have you tried adding in:
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
You will need to add these permissions to your Android Manifest:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
You can also have an additional Spinner come up to have the User select from available Wifi spots by using Scan Result: http://developer.android.com/reference/android/net/wifi/ScanResult.html
and then
WifiManager: http://developer.android.com/reference/android/net/wifi/WifiManager.html
to set the Desired Network if there is not a default connection in place.
Markana has a nice tutorial on using Wifi this way: http://marakana.com/forums/android/examples/40.html
I am trying to get contacts from call log. I can get the contact numbers from main contacts using this code :
public void getContacts(View view) {
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0)
{
try {
to.setText(getContactInfo(intent));
} catch(NullPointerException e) {
// Do nothing ;)
}
}
}
protected String getContactInfo(Intent intent)
{
String phoneNumber = to.getText().toString();
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
if(phoneNumber.endsWith(">"))
phoneNumber += ", "+name;
else
phoneNumber += name;
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{ phoneNumber = phoneNumber + " <" + phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))+">";
}
phones.close();
}
}
cursor.close();
return phoneNumber;
}
What this does is when we click a "Contact" button it open a list with all the contacts, the user can select any contact and that selected contact will be added in the "To" field. I want to do the exactly same thing, but instead of displaying all the contacts i want to display only those who were recently used (call log) for selection.
Also it would be nice if you can tell how to do this with groups also.
I got this going using my own version. i used a dialog and handed it the cursor to the call log. Here is the function:
public void getCallLog() {
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME /* im not using the name but you can*/};
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = getActivity().getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(
getActivity());
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
}
You can use ContactsContract.Contacts.CONTENT_STREQUENT_URI which will give you both Frequently called and Starred contacts.
From API 21 is possible to use this: https://developer.android.com/reference/kotlin/android/provider/CallLog.Calls#CACHED_LOOKUP_URI
CACHED_LOOKUP_URI added in API level 21 static val CACHED_LOOKUP_URI:
String The cached URI to look up the contact associated with the phone
number, if it exists.
This value is typically filled in by the dialer app for the caching
purpose, so it's not guaranteed to be present, and may not be current
if the contact information associated with this number has changed.