Identify missed calls in android and send a message to that number - android

I count the number of missed calls in the log when state is in the Rigging state. Then Count the number of miss call of the Ideal state. Then compare them. But in the ideal state call log is give the same number of miss call. Can some one help me to validate a to recieved call is a miss call or a not.
public class CustomPhoneStateListener extends PhoneStateListener {
Context context;
String callState;
private static boolean wasRiging;
private static int previousNoOfMissCall;
private static int UDF;
public CustomPhoneStateListener(Context context) {
super();
this.context = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
callState = "IDEAL";
if (UDF != TelephonyManager.CALL_STATE_IDLE) {
sendSMSToMissNo(incomingNumber, "Test");
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
callState = "OFFHOOK";
break;
case TelephonyManager.CALL_STATE_RINGING:
callState = "RIGING";
previousNoOfMissCall = this.getMisscallCount();
wasRiging = true;
break;
default:
break;
}
UDF = state;
Log.i(">>>Broadcast", "onCallStateChanged " + callState);
}
public int getMisscallCount() {
String[] projection = { CallLog.Calls.CACHED_NAME,
CallLog.Calls.CACHED_NUMBER_LABEL, CallLog.Calls.TYPE };
String where = CallLog.Calls.TYPE + "=" + CallLog.Calls.MISSED_TYPE;
Cursor c = context.getContentResolver().query(
CallLog.Calls.CONTENT_URI, projection, where, null, null);
c.moveToFirst();
Log.d("CALL", "" + c.getCount()); // do some other operation
return c.getCount();
}
private void sendSMSToMissNo(String phoneNumber, String message) {
if (this.validateMissCall(previousNoOfMissCall)) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
private boolean validateMissCall(int preNoOfMissCall) {
int crtNoOfMissCall = this.getMisscallCount();
Log.d("CALL", "" + "In validate"+crtNoOfMissCall);
if (preNoOfMissCall == crtNoOfMissCall) {
return false;
}
return true;
}
}
public class PhoneStateBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new CustomPhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);
}
}

Related

How to make network call from Background service?

this is my service Interface
public interface ContactService {
void postPhoneContacts(#NonNull ContactServiceListener serviceListener, int id, List<UserProfileInfo> userInfo);
}
This is mybackground service from where i want to make a network call
How to intsantiate Contact Service Interface here? I am getting Null Pointer Exception. From Fragment I am starting this service. Please help me this out
public class UploadContactBgService extends Service {
private ContactService contactService;
private int userId;
#Override
public void onCreate() {
super.onCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
List<UserProfileInfo> contactList = getContactsFromPhone();
EventBus.getDefault().post(new PostContactEvent(contactList));
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
userId = prefs.getInt(LoginPresenter.PREF_USER_ID, 0);
if (userId != 0) {
postPhoneBookContactList(userId, contactList);
}*/
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private List<UserProfileInfo> getContactsFromPhone() {
//Read Column names of ContactsContract table to get contact info from phone book
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
Uri DATA_CONTENT_URI = ContactsContract.Data.CONTENT_URI;
String ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String PHONE_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
String EMAIL_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
String DATA_CONTACT_ID = ContactsContract.Data.CONTACT_ID;
String ADDRESS_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE;
String ORG_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE;
String DATA_MIME_TYPE = ContactsContract.Data.MIMETYPE;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
String EVENT_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE;
String EVENT_START_DATE = ContactsContract.CommonDataKinds.Event.START_DATE;
String NOTE_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE;
String WEB_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE;
String RELATION_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE;
int CONTACT_TYPE_MOBILE = 1;
int CONTACT_TYPE_WORK = 2;
int CONTACT_TYPE_HOME = 3;
int CONTACT_TYPE_WORK_FAX = 4;
int CONTACT_TYPE_HOME_FAX = 5;
int CONTACT_TYPE_PAGER = 6;
int CONTACT_TYPE_OTHER = 7;
int USER_PROFILE_TYPE = 2;
ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(CONTENT_URI, null, null, null,
DISPLAY_NAME + " ASC ");
List<UserProfileInfo> userInfoList = new ArrayList<>();
if (cursor.moveToNext()) {
do {
String contactId = cursor.getString(cursor.getColumnIndex(ID));
UserProfileInfo userInfo = new UserProfileInfo();
UserProfile profile = new UserProfile();
UserType userType = new UserType();
/**
* Querying the table ContactsContract.Data to retrieve individual items like
home phone, mobile phone, work email etc corresponding to each contact
*/
Cursor dataCursor = cr.query(DATA_CONTENT_URI, null,
DATA_CONTACT_ID + "=" + contactId,
null, null);
if (dataCursor.moveToFirst()) {
/**
* checking if respective contactId has contact number or not
* If yes..then only add that user to list
* otherwise read next user
*/
int hasContactNumber = Integer.parseInt(dataCursor.getString(
dataCursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasContactNumber == 0) {
continue;
}
// Getting Display Name
String displayName = dataCursor.getString(dataCursor.getColumnIndex(DISPLAY_NAME));
profile.setName(displayName);
do {
// Getting Phone numbers
List<Contact> phones = new ArrayList<>();
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(PHONE_CONTENT_ITEM_TYPE)) {
Contact contactNum = new Contact();
ContactTypeDm contactTypeDm = new ContactTypeDm();
switch (dataCursor.getInt(dataCursor.getColumnIndex("data2"))) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
String homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(homePhone);
contactNum.setContactNumber(homePhone);
contactTypeDm.setContactTypeId(CONTACT_TYPE_HOME);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
String mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(mobilePhone);
contactNum.setContactNumber(mobilePhone);
contactTypeDm.setContactTypeId(CONTACT_TYPE_MOBILE);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
String workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(workPhone);
contactNum.setContactNumber(workPhone);
contactTypeDm.setContactTypeId(CONTACT_TYPE_WORK);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
String other = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(other);
contactNum.setContactNumber(other);
contactTypeDm.setContactTypeId(CONTACT_TYPE_OTHER);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
}
userInfo.setContacts(phones);
}
// Getting EMails
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(EMAIL_CONTENT_ITEM_TYPE)) {
switch (dataCursor.getInt(dataCursor.getColumnIndex("data2"))) {
case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
String homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setEmail(homeEmail);
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
String workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setEmail(workEmail);
break;
}
}
// Getting Organization details
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(ORG_CONTENT_ITEM_TYPE)) {
String companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
String title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
profile.setOrgName(companyName);
profile.setTitle(title);
}
// Getting BDay
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(EVENT_CONTENT_ITEM_TYPE)) {
int indexEvent = dataCursor.getColumnIndex(EVENT_START_DATE);
String dobStr = dataCursor.getString(indexEvent);
profile.setBDay(dobStr);
}
//Getting Note
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(NOTE_CONTENT_ITEM_TYPE)) {
String note = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setNotes(note);
}
//Getting Postal Address Details...
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(ADDRESS_CONTENT_ITEM_TYPE)) {
String street = dataCursor.getString(dataCursor.getColumnIndex("data4"));
String city = dataCursor.getString(dataCursor.getColumnIndex("data7"));
String state = dataCursor.getString(dataCursor.getColumnIndex("data8"));
String postalCode = dataCursor.getString(dataCursor.getColumnIndex("data9"));
Address addressInfo = new Address();
addressInfo.setStreet(street);
addressInfo.setCity(city);
addressInfo.setZip(postalCode);
addressInfo.setState(state);
userInfo.setAddress(addressInfo);
}
//Getting Website
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(WEB_CONTENT_ITEM_TYPE)) {
String webUrl = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setWebsite(webUrl);
}
//Getting Relation
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(RELATION_CONTENT_ITEM_TYPE)) {
String relationship = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setRelationShip(relationship);
}
}
while (dataCursor.moveToNext());
}
userType.setUserTypeId(USER_PROFILE_TYPE);
profile.setUserType(userType);
userInfo.setUserProfile(profile);
userInfoList.add(userInfo);
} while (cursor.moveToNext());
}
return userInfoList;
}
public void postPhoneBookContactList(int id, List<UserProfileInfo> userInfoList) {
contactService.postPhoneContacts(new ContactServiceListener() {
#Override
public void onSuccess(UserProfileInfo responseBody) {
EventBus.getDefault().post(new GetSyncedContactListEvent(responseBody));
}
#Override
public void onError(String error) {
}
}, id, userInfoList);
}
}

ClearCallLog not updating listview

I am a school student learning android. I am doing a simple contacts app! When i click on clear calllog button, my recent contacts listview remains the same. Its not getting cleared. But when i close the app and reopen again, the recent contacts fragment is getting cleared! I debugged the code, code is not entering after cursor.movetoNext() line when i click on clearcall log. Kindly help me techies!
I programmed like updateFragment2ListView() gets called when i clear the call log button in menu!
public class RecentContacts extends Fragment {
HashMap contactMap = new HashMap();
View rootView;
RecentAdapter rr;
ListView list;
private static final int PERMISSIONS_REQUEST_READ_CALLLOG = 100;
Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_recent_contacts, container, false);
list = (ListView) rootView.findViewById(R.id.customlist);
getRecentContacts();
rr = new RecentAdapter(contactMap, getActivity());
list.setAdapter(rr);
return rootView;
}
public void updateFragment2ListView() {
getRecentContacts();
rr.notifyDataSetChanged();
list.setAdapter(rr);
System.out.println("Fragment recent updated-updateFragment2listview");
}
#Override
public void onResume() {
getRecentContacts();
rr.notifyDataSetChanged();
System.out.println("Fragment recent updated- onresume");
super.onResume();
}
#Override
public void onStart() {
System.out.println("Fragment recent onstart");
super.onStart();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void getRecentContacts() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getContext().checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CALL_LOG}, PERMISSIONS_REQUEST_READ_CALLLOG);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
System.out.println("Security check ok");
} else {
System.out.println("Entered recent onstart");
int i=0;
Uri queryUri = android.provider.CallLog.Calls.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts._ID,
CallLog.Calls._ID,
CallLog.Calls.NUMBER,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.DATE,
CallLog.Calls.TYPE};
String sortOrder = String.format("%s limit 500 ", CallLog.Calls.DATE + " DESC");
try {
System.out.println("Entering cursor in recent contacts");
cursor = getActivity().getContentResolver().query(queryUri, projection, null, null, sortOrder);
System.out.println("Entered cursor in recent contacts");
} catch (SecurityException e) {
Log.e("", "");
}
while (cursor.moveToNext()) {
System.out.println("Entered cursor.movetoNext recent contacts");
String phoneNumber = cursor.getString(cursor
.getColumnIndex(CallLog.Calls.NUMBER));
System.out.println("Entered phone number in recent contacts");
String title = (cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
int duration1 = cursor.getColumnIndex(CallLog.Calls.DURATION);
System.out.println("Duration" + duration1);
System.out.println("Entered duration in recent contacts");
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
System.out.println("Call Date" + callDayTime);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
String callType = cursor.getString(type);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
System.out.println("Call type" + dir);
// if (phoneNumber == null || title == null) continue;
String uri = "tel:" + phoneNumber;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
String intentUriString = intent.toUri(0);
contactMap.put(i, new RecentPojo(title, phoneNumber, duration1, false, callDayTime, dir));
// Toast.makeText(this,title,Toast.LENGTH_SHORT).show();
i++;
}
cursor.close();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if ((requestCode == PERMISSIONS_REQUEST_READ_CALLLOG)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
System.out.println("");
getRecentContacts();
} else {
Toast.makeText(getContext(), "Until you grant the permission, we cannot display the names", Toast.LENGTH_SHORT).show();
}
}
}
}
You have to call rr.notifyDataSetChanged(); when you clear it so the ListView is refreshed.

contentProvider and search by name and not ID Android

it's the first time I'm using the content provider.
so I have this:
public class ContactsContentProvider extends ContentProvider {
private ContactsDatabaseHelper dbHelper;
private static final UriMatcher uriMatcher =
new UriMatcher(UriMatcher.NO_MATCH);
private static final int ONE_CONTACT = 1;
private static final int CONTACTS = 2;
private static final int CONTACT = 3;
static {
uriMatcher.addURI(ContactsDatabaseDescription.AUTHORITY,
Contact.TABLE_NAME + "/#", ONE_CONTACT);
uriMatcher.addURI(ContactsDatabaseDescription.AUTHORITY,
Contact.TABLE_NAME, CONTACTS);
uriMatcher.addURI(ContactsDatabaseDescription.AUTHORITY,
Contact.TABLE_NAME + "/*" , CONTACT);
}
#Override
public boolean onCreate() {
dbHelper = new ContactsDatabaseHelper(getContext());
return true;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Cursor query(Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Contact.TABLE_NAME);
switch (uriMatcher.match(uri)) {
case ONE_CONTACT:
queryBuilder.appendWhere(
Contact._ID + "=" + uri.getLastPathSegment());
break;
case CONTACTS:
break;
default:
throw new UnsupportedOperationException(
getContext().getString(R.string.invalid_query_uri) + uri);
}
Cursor cursor = queryBuilder.query(dbHelper.getReadableDatabase(),
projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
// insert a new contact in the database
#Override
public Uri insert(Uri uri, ContentValues values) {
Uri newContactUri = null;
switch (uriMatcher.match(uri)) {
case CONTACTS:
// insert the new contact--success yields new contact's row id
long rowId = dbHelper.getWritableDatabase().insert(
Contact.TABLE_NAME, null, values);
if (rowId > 0) {
newContactUri = Contact.buildContactUri(rowId);
getContext().getContentResolver().notifyChange(uri, null);
}
else
throw new SQLException(
getContext().getString(R.string.insert_failed) + uri);
break;
default:
throw new UnsupportedOperationException(
getContext().getString(R.string.invalid_insert_uri) + uri);
}
return newContactUri;
}
#Override
public int update(Uri uri, ContentValues values,
String selection, String[] selectionArgs) {
int numberOfRowsUpdated; // 1 if update successful; 0 otherwise
switch (uriMatcher.match(uri)) {
case ONE_CONTACT:
String id = uri.getLastPathSegment();
numberOfRowsUpdated = dbHelper.getWritableDatabase().update(
Contact.TABLE_NAME, values, Contact._ID + "=" + id,
selectionArgs);
break;
default:
throw new UnsupportedOperationException(
getContext().getString(R.string.invalid_update_uri) + uri);
}
if (numberOfRowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return numberOfRowsUpdated;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int numberOfRowsDeleted;
switch (uriMatcher.match(uri)) {
case ONE_CONTACT:
String id = uri.getLastPathSegment();
numberOfRowsDeleted = dbHelper.getWritableDatabase().delete(
Contact.TABLE_NAME, Contact._ID + "=" + id, selectionArgs);
break;
default:
throw new UnsupportedOperationException(
getContext().getString(R.string.invalid_delete_uri) + uri);
}
if (numberOfRowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return numberOfRowsDeleted;
}
}
My database is
public class ContactsDatabaseDescription {
public static final String AUTHORITY =
"com.example.afran.bdcontacts.data";
private static final Uri BASE_CONTENT_URI =
Uri.parse("content://" + AUTHORITY);
public static final class Contact implements BaseColumns {
public static final String TABLE_NAME = "contacts"; // table's name
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(TABLE_NAME).build();
public static final String COLUMN_FIRST_NAME = "firstName";
public static final String COLUMN_LAST_NAME = "lastName";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_TYPE = "type";
public static Uri buildContactUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
}
}
and on this fragment I read one last name (search) and I want to find the contact and I do not know how
public class DetailFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
public interface DetailFragmentListener {
void onContactDeleted();
void onEditContact(Uri contactUri);
}
private static final int CONTACT_LOADER = 0;
private DetailFragmentListener listener;
private Uri contactUri;
private TextView prenomTextView;
private TextView nomTextView;
private TextView emailTextView;
private TextView typeTextView;
#Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (DetailFragmentListener) context;
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true);
Bundle arguments = getArguments();
if (arguments != null)
contactUri = arguments.getParcelable(MainActivity.CONTACT_URI);
View view =
inflater.inflate(R.layout.fragment_detail, container, false);
prenomTextView = (TextView) view.findViewById(R.id.firstNameTextView);
nomTextView = (TextView) view.findViewById(R.id.lastNameTextView);
emailTextView = (TextView) view.findViewById(R.id.emailTextView);
typeTextView = (TextView) view.findViewById(R.id.typeTextView);
getLoaderManager().initLoader(CONTACT_LOADER, null, this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
listener.onEditContact(contactUri);
return true;
case R.id.action_delete:
deleteContact();
return true;
case R.id.action_search:
searchContact();
return true;
}
return super.onOptionsItemSelected(item);
}
private void searchContact() {
final EditText input = new EditText(getContext());
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.menuitem_recherche);
builder.setMessage(R.string.label_lastName);
builder.setView(input);
builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
return;
}
});
builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
builder.create().show();
}
private void deleteContact() {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.confirm_title);
builder.setMessage(R.string.confirm_message);
builder.setPositiveButton(R.string.button_delete, new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog, int button) {
getActivity().getContentResolver().delete(
contactUri, null, null);
listener.onContactDeleted();
}
}
);
builder.setNegativeButton(R.string.button_cancel, null);
builder.create().show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader;
switch (id) {
case CONTACT_LOADER:
cursorLoader = new CursorLoader(getActivity(),
contactUri,
null,
null,
null,
null);
break;
default:
cursorLoader = null;
break;
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
int firstIndex = data.getColumnIndex(ContactsDatabaseDescription.Contact.COLUMN_FIRST_NAME);
int lastIndex = data.getColumnIndex(ContactsDatabaseDescription.Contact.COLUMN_LAST_NAME);
int emailIndex = data.getColumnIndex(ContactsDatabaseDescription.Contact.COLUMN_EMAIL);
int typeIndex = data.getColumnIndex(ContactsDatabaseDescription.Contact.COLUMN_TYPE);
prenomTextView.setText(data.getString(firstIndex));
nomTextView.setText(data.getString(lastIndex));
emailTextView.setText(data.getString(emailIndex));
typeTextView.setText(data.getString(typeIndex));
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) { }
}
It is simple to search for a match of any column in your table. You simply need the contentUri, and where and whereArgs parameters for the query. Ensure your Uri points to the whole table. Assuming you want to match columns called "first_name" and "surname" with Strings called firstName and surname.
String where = "first_name =? and surname =?";
String[] whereArgs = {firstName, surname};
You can use parentheses and "and" and "or" to construct more complex queries. With numerical fields you can use > and < etc. You must ensure whereArgs has as many elements as where has "?"

Tracking phonecalls

I am trying to track phone call states and log. I need phone numbers, name(if it is a saved contact) and time of the call and duration. The problem is that getContentResolver() method cannot be called, its commented in code.
public class PhoneStateBroadcastReciever extends BroadcastReceiver {
Context m_context;
String m_number = null;
String m_startTime = null;
String m_endTime = null;
SharedPreferences m_sharedPrefs;
Editor editor;
static String PREFS_NUMBER;
static String PREFS_START_TIME;
static String PREFS_END_TIME;
#Override
public void onReceive(Context context, Intent intent) {
m_sharedPrefs = m_context.getSharedPreferences("MyPrefs", 0);
editor = m_sharedPrefs.edit();
Bundle bundle = intent.getExtras();
if (bundle == null)
return;
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if ((state != null) &&
(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))) {
Log.i("TAG", "incoming call");
Uri contactUri = intent.getData();
String[] projection = { Phone.DISPLAY_NAME };
//i cannot use getContentResolver()
Cursor cursor = getContentResolver()..query(contactUri, projection, null,
null, null);
int columnName = cursor.getColumnIndex(Phone.DISPLAY_NAME);
String contactName = cursor.getString(columnName);
m_number = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
editor.putString(PREFS_NUMBER, m_number);
editor.commit();
} else if(state == null) {
Log.i("TAG", "outgoing call");
Uri contactUri = intent.getData();
String[] projection = { Phone.DISPLAY_NAME };
//i cannot use getContentResolver()
Cursor cursor = getContentResolver()..query(contactUri, projection, null,
null, null);
int columnName = cursor.getColumnIndex(Phone.DISPLAY_NAME);
String contactName = cursor.getString(columnName);
m_number = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
editor.putString(PREFS_NUMBER, m_number);
editor.commit();
} else if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.i("TAG", "off hook");
Time dtstart = new Time(Time.getCurrentTimezone());
dtstart.setToNow();
m_startTime = dtstart.format("%k:%M:%S");
editor.putString(PREFS_START_TIME, m_startTime);
editor.commit();
} else if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
Log.i("TAG", "on idle");
Time dtend = new Time(Time.getCurrentTimezone());
dtend.setToNow();
m_endTime = dtend.format("%k:%M:%S");
editor.putString(PREFS_END_TIME, m_endTime);
editor.commit();
}
}
this is the service class:
public class TrackerService extends Service {
PhoneStateBroadcastReciever receiver;
#Override
public void onCreate() {
receiver = new PhoneStateBroadcastReciever();
IntentFilter filter = new IntentFilter();
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(receiver, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "starting service", Toast.LENGTH_SHORT).show();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
Use the Context to invoke the contentResolver(). Something like that:
context.getContentResolver()....

I am not getting the outgoing call phone number? both in emulator and real phone also getting null

call.java:
public class Call extends Activity{
boolean timerhasstarted;
Intent callIntent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
call();
}
void call()
{
String num="7829893070";
callIntent=new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+num));
if(!timerhasstarted)
{
startActivity(callIntent);
ct.start();
timerhasstarted=true;
}
else {
ct.cancel();
timerhasstarted=false;
Toast.makeText(getApplicationContext(), "timer not started ",Toast.LENGTH_SHORT ).show();
}
}
CountDownTimer ct=new CountDownTimer(10000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Toast.makeText(getApplicationContext(), "time: "+millisUntilFinished/1000, Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "time over ..",Toast.LENGTH_SHORT ).show();
OutgoingCallReceiver out=new OutgoingCallReceiver();
out.onReceive(getApplicationContext(),callIntent);
}
};
}
OutgoingCallReceiver.java :
public class OutgoingCallReceiver extends BroadcastReceiver {
public static final String ABORT_PHONE_NUMBER = "7204230210";
private static final String OUTGOING_CALL_ACTION = "android.intent.action.NEW_OUTGOING_CALL";
private static final String INTENT_PHONE_NUMBER = "android.intent.extra.PHONE_NUMBER";
String TAG="EMERGENCY";
#Override
public void onReceive(final Context context, final Intent intent) {
Log.v(TAG, "OutgoingCallReceiver .. : onReceive");
Log.i( "l", "onReceive()" );
Log.i( "l", "context: " + context );
Log.i( "l", "intent: " + intent );
String getphoneNumber = this.getResultData();
Log.i(TAG,"getphnum "+getphoneNumber);
String phoneNumber1 = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i(TAG,"PHONE_NUMBER "+phoneNumber1);
Toast.makeText(context, "PHONE_NUMBER "+phoneNumber1, Toast.LENGTH_LONG).show();
if (intent.getAction().equals(OutgoingCallReceiver.OUTGOING_CALL_ACTION)) {
Log.v(TAG, "OutgoingCallReceiver NEW_OUTGOING_CALL received");
Toast.makeText(context, "OutgoingCallReceiver NEW_OUTGOING_CALL received", Toast.LENGTH_SHORT).show();
// get phone number from bundle
String phoneNumber = intent.getExtras().getString("android.intent.action.NEW_OUTGOING_CALL");
if ((phoneNumber != null) && phoneNumber.equals(OutgoingCallReceiver.ABORT_PHONE_NUMBER)) {
Toast.makeText(context, "NEW_OUTGOING_CALL intercepted to number 123-123-1234 - aborting call",
Toast.LENGTH_LONG).show();
abortBroadcast();
// this.setResultData(ABORT_PHONE_NUMBER);
}
}
}
phone number
String phoneNumber = intent.getExtras().getString("android.intent.action.NEW_OUTGOING_CALL"); //getting null number
String phoneNumber =
intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); //getting null number
here of both which statement is write to get phonenumber?
want to get the outgoing phone number ,but in logcat and in my phone i checked, it is showing null value. why?
what statement that i have to write to hold the outgoing caall phonenum?(single call only i have placed).
setResultData(null)
with this method, have to end the call,but not ending the call..in my
phone? what i have to do to end call in my phone?
logcat
03-15 11:50:06.062: V/EMERGENCY(490): OutgoingCallReceiver .. : onReceive
03-15 11:50:06.082: I/l(490): onReceive()
03-15 11:50:06.082: I/l(490): context: android.app.Application#44f3f8b0
03-15 11:50:06.082: I/l(490): intent: Intent { act=android.intent.action.CALL dat=tel:7829893070 }
03-15 11:50:06.113: I/EMERGENCY(490): getphnum null
03-15 11:50:06.122: I/EMERGENCY(490): PHONE_NUMBER null
03-15 11:50:10.522: D/dalvikvm(264): GC_EXPLICIT freed 71 objects / 3424 bytes in 189ms
03-15 11:50:15.653: D/dalvikvm(166): GC_EXPLICIT freed 4298 objects / 244840 bytes in 218ms
here getphnum & PHONE_NUMBER shows null. by toast also i an knowing null in phone device also.
you can try this for activity then after do this for background service
public void outgoingRecord()
{
Cursor c = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI,
null,
null,
null,
android.provider.CallLog.Calls.DATE+ " DESC");
startManagingCursor(c);
int numberColumn = c.getColumnIndex(
android.provider.CallLog.Calls.NUMBER);
int dateColumn = c.getColumnIndex(
android.provider.CallLog.Calls.DATE);
// type can be: Incoming, Outgoing or Missed
int typeColumn = c.getColumnIndex(
android.provider.CallLog.Calls.TYPE);
int durationColumn=c.getColumnIndex(
android.provider.CallLog.Calls.DURATION);
// Will hold the calls, available to the cursor
ArrayList<String> callList = new ArrayList<String>();
try{
boolean moveToFirst=c.moveToFirst();
Log.e("MOVETOFIRST", "moveToFirst="+moveToFirst);
}
catch(Exception e)
{
Log.e("MOVETOFIRSTERROR","MOVETOFIRST Error="+e.toString());
}
String callerPhoneNumber = c.getString(numberColumn);
int callDate = c.getInt(dateColumn);
int callType = c.getInt(typeColumn);
int duration=c.getInt(durationColumn);
Log.d("CALLS", "callDate="+callDate);
switch(callType){
case android.provider.CallLog.Calls.INCOMING_TYPE:
Log.d("INCOMINGCALLLOG", "CallerPhoneNum="+
callerPhoneNumber+" "+"Duration="+duration);
break;
case android.provider.CallLog.Calls.MISSED_TYPE:
break;
case android.provider.CallLog.Calls.OUTGOING_TYPE:
Log.d("OUTGOINGCALLLOG",
"CallerPhoneNum="+ callerPhoneNumber+" "+"Duration="+duration);
break;
}
}

Categories

Resources