I am working on an android project and I would like to create an application that intercept the inbound calls.How to assign a check box at contact list, in order to be able to select multiple contact persons once?
Here is my code:
//main activity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button)findViewById(R.id.add_reminder);
manage = (Button)findViewById(R.id.manage_reminders);
add.setOnClickListener(this);
manage.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId())
{
case R.id.manage_reminders:
break;
case R.id.add_reminder:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
cursor.moveToNext();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(this, "Contect LIST = "+name, Toast.LENGTH_LONG).show();
}
}//onActivityResult
}
Take a look here: http://www.krvarma.com/2010/08/detecting-incoming-and-outgoing-calls-in-android/
Just make an BroadcastReceiver that listens to:
android.intent.action.PHONE_STATE
If the phone state is 'Ringing', then there is an incoming call.
TelephonyManager.EXTRA_STATE
Like:
public class IncomingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(null == bundle)
return;
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
{
String phonenumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i("IncomingCallReceiver","Incoming Number: " + phonenumber);
}
}
}
Now the phone number will be printed in logcat.
Related
I am making a birthday wisher app, everthing works fine but I want that user can select image from gallary and it passes to 2nd activity, when timer is finised, I used ticker coundown in this.
My MainActivity
public class MainActivity extends AppCompatActivity {
CircularView circularViewWithTimer;
EditText entertime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
entertime = (EditText) findViewById(R.id.Txt_time);
circularViewWithTimer = findViewById(R.id.circular_view);
CircularView.OptionsBuilder builderWithTimer =
new CircularView.OptionsBuilder()
.shouldDisplayText(true)
.setCounterInSeconds(15)
.setCircularViewCallback(new CircularViewCallback() {
#Override
public void onTimerFinish() {
String name = entertime.getText().toString();
Intent i = new Intent(MainActivity.this, Bday_page.class);
i.putExtra("text", name);
startActivity(i);
finish();
}
#Override
public void onTimerCancelled() {
// Will be called if stopTimer is called
Toast.makeText(MainActivity.this, "CircularCallback: Timer Cancelled ", Toast.LENGTH_SHORT).show();
}
});
circularViewWithTimer.setOptions(builderWithTimer);
}
public void btn_pause(View view) {
circularViewWithTimer.pauseTimer();
}
public void btn_start(View view) {
MediaPlayer mMediaPlayer;
if(entertime.getText().toString().isEmpty()){
Toast.makeText(this, "Enter name of bday boy", Toast.LENGTH_SHORT).show();
}
else {
circularViewWithTimer.startTimer();
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this,R.raw.count);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
}
public void btn_resume(View view) {
circularViewWithTimer.resumeTimer();
}
}
My 2nd Activity
public class Bday_page extends AppCompatActivity {
TextView nameuser;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bday_page);
nameuser = (TextView)findViewById(R.id.txt_imagename);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.happybady);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
Intent i = getIntent();
nameuser.setText(i.getStringExtra("text"));
}
}
first of all you have to request the storage permission in the manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
after that in your MainActivity make your onTimerFinish methods like these
#Override
public void onTimerFinish() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent,1777);
}
now you requsted the image from Galary then add onActivityResult method to your main activity to receive the image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
Uri uri = data.getData();
Cursor cursor;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
String name = entertime.getText().toString();
Intent i = new Intent(MainActivity.this, Bday_page.class);
i.putExtra("text", name);
i.putExtra("imagePath",picturePath )
startActivity(i);
finish();
}}}
now you get the path of selected image and send it to the next activity
and in your 2nd Activity receive the image like these
Intent i = getIntent();
nameuser.setText(i.getStringExtra("text"));
String imagePath = i.getStringExtra("imagePath") //add these
now you have the image Path in the new activity you can do what you want to do with it
Here is the code:
button.setOnClickListener(new View.OnClickListener() {
#Override public void onClick (View view){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}); return view;}
public void but(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
Uri uri = data.getData();
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
if (phoneNo.startsWith("+")) {
if (phoneNo.length() == 13) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
if (phoneNo.length() == 16) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
} else {
editText.setText(phoneNo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You may be facing any of the following scenarios that led to the crash :
Your button is not declared and initiated properly in the onCreate() method of your main class. So please check if you have the below code in your onCreate() method :
Button button = (Button) findViewById(R.id.button);
Your app reads contacts from the user device I believe. In that case, please check if you have necessary permission to read contacts. For that, just check if the below line is included in the AndroidManifest.xml file :
<uses-permission android:name="android.permission.READ_CONTACTS" />
Check if you have permission to call the appropriate intent.
Your logcat trace will contain the exact line of code that led to the crash and the error code. So if you paste the logcat info here, you can get help.
Good day!
i am quite new in programming and i am trying to make a simple android app. i have here 2 edittext and 2 buttons inside my activity and what i want them to do is get the number of prefered contacts to text and the 1st edittext and 1st button succeeded but my problem is the button 2 also put the number on the 1st edittext that is supposed to put in 2nd edittext any idea?
this is my code..
public class SA extends Activity {
EditText con1;
EditText con2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_s);
con1 = (EditText) findViewById(R.id.cnum1);
con2 = (EditText) findViewById(R.id.cnum2);
((Button)findViewById(R.id.btnSelectContact1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.btnSelectContact2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v2) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent2.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent2, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,},
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
showSelectedNumber(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
protected void onActivityResult2(int requestCode2, int resultCode2, Intent data2) {
if (data2 != null) {
Uri uri2 = data2.getData();
if (uri2 != null) {
Cursor c2 = null;
try {
c2 = getContentResolver().query(uri2, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,},
null, null, null);
if (c2 != null && c2.moveToNext()) {
String number2 = c2.getString(0);
showSelectedNumber(number2);
}
} finally {
if (c2 != null) {
c2.close();
}
}
}
}
}
public void showSelectedNumber(String number) {
con1.setText(number);
}
public void showSelectedNumber2(String number2) {
con2.setText(number2);
}
No need of onActivityResult2() because startActivityForResult() gives you result back in onActivityResult() method.
So now your question would be, how you can manage different requests? Well, that you can do by passing different request code while calling startActivityForResult().
For example:
startActivityForResult(intent, 1); // first request
startActivityForResult(intent, 2); // second request
// you can pass any random number as a request code
Now you just need to perform the operations according to the request code received back in onActivityResult() method.
For example:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if(requestCode == 1) {
...
...
} else if (requestCode == 2) {
...
...
}
}
}
I try to pass a string from one activity to another activity.
This is the coding in Activity A:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("UserName", UserName);
Log.i(Tag, "UserName1: "+ UserName);
super.onSaveInstanceState(savedInstanceState);
}
In Activity B I use this code to get the string:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.i(Tag, "UserName2: "+ UserName);
}
But the logcat shown the first log "UserName1" when I clikc the open to Activity B,
and show the second log "UserName2" as "null".
May I know what wrong with my code?
What I want to do is Activity A pass the String in Activity B when I click the "button" and intent to Activity B. So I can get the String value in Activity B.
Any Idea? Cause I getting error when using intent.putStringExtra() and getintent.getStringExtra(), so I change to use onSaveInstanceState (), but still having problem.
EDIT:
This is my original code, I can get the String in Activity B, but unexpected I can't save my data in Sqlite. If remove the putString Extra then everything go smoothly.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addItem = new Intent(ItemActivity.this, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
addItem.putStringExtra("UserName", UserName);
Log.e(Tag, "UseName: "+ UserName);
startActivity(addItem);
return super.onOptionsItemSelected(item);
}
Code in Activity B:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
UserName = (String) getIntent().getStringExtra("UserName");
Log.e(Tag, "UserName3: "+ UserName);
}
Full code for Activity B:
public class AddEditItem extends Activity implements OnItemSelectedListener {
private static final String Tag = null;
private EditText inputItemName;
private EditText inputItemCondition;
private EditText inputEmail;
private Button btnGal, btnConfirm;
private Bitmap bmp;
private ImageView ivGalImg;
private Spinner spinner;
String[] category = {"Books", "Clothes & Shoes", "Computer", "Electronics", "Entertainment", "Food & Drinks",
"Furnitures", "Mobile Phone", "Other", "UKM"};
String selection;
String filePath, itemName, itemCondition;
String UserName, user;
private int id;
private byte[] blob=null;
byte[] byteImage2 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.e(Tag, "UserName2: "+ UserName);
//UserName = (String) getIntent().getStringExtra("UserName");
//Log.e(Tag, "UserName3: "+ UserName);
}
private void setUpViews() {
inputItemName = (EditText)findViewById(R.id.etItemName);
inputItemCondition = (EditText)findViewById(R.id.etItemCondition);
inputEmail = (EditText)findViewById(R.id.etEmail);
ivGalImg = (ImageView) findViewById(R.id.ivImage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddEditItem.this, android.R.layout.simple_spinner_dropdown_item, category);
spinner = (Spinner)findViewById(R.id.spnCategory);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
user=extras.getString("user");
inputItemName.setText(extras.getString("name"));
inputItemCondition.setText(extras.getString("condition"));
inputEmail.setText(extras.getString("email"));
selection = extras.getString("category");
byteImage2 = extras.getByteArray("blob");
if (byteImage2 != null) {
if (byteImage2.length > 3) {
ivGalImg.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2,0,byteImage2.length));
}
}
}
btnGal = (Button) findViewById(R.id.bGallary);
btnGal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
btnConfirm = (Button) findViewById(R.id.bConfirm);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputItemName.getText().length() != 0 && inputItemCondition.getText().length() != 0
&& inputEmail.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveItemTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveItem();
return null;
}
#Override
protected void onPostExecute(Object result) {
Toast.makeText(getApplicationContext(),
"Item saved", Toast.LENGTH_LONG)
.show();
finish();
}
};
saveItemTask.execute((Object[]) null);
Toast.makeText(getApplicationContext(),
"Item saved reconfirm", Toast.LENGTH_LONG)
.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditItem.this);
alert.setTitle("Error In Save Item");
alert.setMessage("You need to fill in all the item details");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveItem() {
if(bmp!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=byteImage2;}
ItemSQLiteConnector sqlCon = new ItemSQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertItem(UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
else {
sqlCon.updateItem(id, UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
bmp = BitmapFactory.decodeFile(filePath);
ivGalImg.setImageBitmap(bmp);
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view;
selection = tv.getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
onSaveInstanceState is not used in that purpose, its used to save your activity state on for example orientation change, or when you leave an activity and get back to it.
What you need is to use intents.
Other than starting activity, intents can also carry some information throughout app, like this:
This would be activity 1:
Intent = new Intent (getApplicationContext(), Activity2.class);
intent.putExtra("UserName", UserName);
startActivity(intent);
and to recover it in second activity use:
String username = getIntent().getExtras().getString("UserName");
May I know what wrong with my code?
onSaveInstanceState() has nothing to do with passing data between activities. Instead, you need to put your string in an extra on the Intent used with startActivity().
Cause I getting error when using intent.putExtra() and getintent.getExtra()
Since that is the correct approach (albeit using getStringExtra()), please go back to it and fix whatever error you are encountering.
I want to open the native Contact activity, not the Contacts list as I already have done that, but a particular contact information using the native activity.
The special requirement here is that all I want is to display the contact's information but not allowing the user to click anything.
I can open the activity with this code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != 1) {
return;
}
if(resultCode != Activity.RESULT_OK) {
return;
}
Uri selectedUserUri = data.getData();
this.onContactSelected(selectedUserUri);
}
private void onContactsButtonClick() {
startActivityForResult(new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI), 1);
}
private void onContactSelected(Uri selectedUserUri) {
startActivityForResult(new Intent(Intent.ACTION_VIEW, selectedUserUri), 2);
}
I need the user not to be able to click anything because that's not part of the functionalities of my application, in the worst case I would need the activity to report me the clicked phone number or e-mail address instead of opening the dialer or a web browser.
Any help will be greatly appreciated.
Mike
Try this below code for start pick contacts activity like this code write button click event contacts:
try
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
}
catch (Exception e) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
after get contact phone number below code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
try
{
if (requestCode == PICK_CONTACT)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
cursor.moveToNext();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String phone=cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phoneNumber="test";
if ( phone.equalsIgnoreCase("1"))
phone = "true";
else
phone = "false" ;
if (Boolean.parseBoolean(phone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
Toast.makeText(this, "You are selected Contact name "+name, Toast.LENGTH_LONG).show();
if(phone_no.getText().length()!=0)
{
phone_no.setText(phone_no.getText().toString()+","+phoneNumber);
}
else
{
phone_no.setText(phoneNumber);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
}
this function pick a contact assign phone_no Editext this is not allow make a call!
Note:this function copy paste after onCreate() method like below format:
#Override
public void onCreate(Bundle savedInstanceState) {
------------Your Code ---------
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
------------
}