I have an activity named MainActivity.
In which I have started another activity (ContentDetails)
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, id);
Intent intent = new Intent(this, ContactDetails.class);
intent.setData(contactUri);
startActivity(intent);
}
And in ContactDetails.java I have written code to make a phone call.
but when I end call. It finishes all application instead of redirecting to base activity
following is the code of ContactDetails.java
public class ContactDetails extends Activity{
TextView nameField = null;
TextView phoneField = null;
TextView idField = null;
final Context context = this;
private Button button;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
idField = (TextView) findViewById(R.id.contact_id);
nameField = (TextView) findViewById(R.id.contact_name);
phoneField = (TextView) findViewById(R.id.contact_phone);
button = (Button) findViewById(R.id.call_button);
// add PhoneStateListener
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager;
telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
// add button listener
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:03577899456"));
startActivity(callIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
Cursor cursor = managedQuery(getIntent().getData(), null, null, null, null);
cursor.moveToFirst();
//idField.setText(cursor.getString(cursor.getColumnIndex(People._ID)));
nameField.setText(cursor.getString(cursor.getColumnIndex(People.DISPLAY_NAME)));
phoneField.setText(cursor.getString(cursor.getColumnIndex(People.NAME)));
}
private class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
String LOG_TAG = "LOGGING 123";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
Log.i(LOG_TAG, "OFFHOOK");
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended, need detect flag
// from CALL_STATE_OFFHOOK
Log.i(LOG_TAG, "IDLE");
if (isPhoneCalling) {
Log.i(LOG_TAG, "restart app");
// restart app
try{
// Intent intentAndroid = new Intent().setClass(this, ContactList.class);
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}catch (Exception e) {
// TODO: handle exception
}
isPhoneCalling = false;
}
}
}
}
}
Actually, I think you have to use
startActivityForResult(callIntent, <RESULT_OK>);
instead of
startActivity(callIntent);
And override onActivityResult() in your ContactDetails Activity.
Try this and let me know what happen..
Also from your code I suggest you to don't use of Flag i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); As its clear the current Activities state Task.
Related
I would like to make two calls in a row in an android app. Upon clicking button the app calls the first number. I created the broadcastreceiver below, that detects when the first call ends. It should write out that "First call ended" and then call the second number. It does not seem working. Can anybody spot the mistake in my code?
public class MainActivity extends AppCompatActivity {
public void calling(String phone) {
Intent callIntent = new Intent(Intent.ACTION_CALL)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent.setData(Uri.parse("tel:" + phone));
callIntent.putExtra("com.android.phone.extra.slot", 1);
startActivity(callIntent);
Intent intent = new Intent(this, CallReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243 , intent, 0);
startActivity(callIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) this.findViewById(R.id.CallButton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calling("+36309577686");
}
});
}
public class CallReciever extends BroadcastReceiver {
private Context mContext;
private CustomPhoneStateListener mPhoneListener;
private String incoming_nr;
private int prev_state;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (mPhoneListener == null) {
mPhoneListener = new CustomPhoneStateListener();
// TelephonyManager object
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// Register our listener with TelephonyManager
telephony.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
/* Custom PhoneStateListener */
class CustomPhoneStateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (!TextUtils.isEmpty(incomingNumber)) {
incoming_nr = incomingNumber;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
prev_state = state;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
prev_state = state;
break;
case TelephonyManager.CALL_STATE_IDLE:
if ((prev_state == TelephonyManager.CALL_STATE_OFFHOOK)) {
// A call has now ended
//it writes out the call end, but does not call. why?
Toast.makeText(mContext, "Call End", Toast.LENGTH_SHORT).show();
calling("+36303853440");
prev_state = state;
}
else if ((prev_state == TelephonyManager.CALL_STATE_RINGING)) {
// Rejected or Missed call
Toast.makeText(mContext, "Rejected Call", Toast.LENGTH_SHORT).show();
prev_state = state;
}
break;
}
}
}
}
}
You are not registering the CallReciever anywhere. Try this
Button b = (Button) this.findViewById(R.id.CallButton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calling("+36309577686");
registerReceiver(new CallReceiver());
}
});
Then unregister the receiver on broadcast is received
Is this possible? I have 2 activities and 2 layouts, but I want to reference a view which belongs to another .xml and not the one being inflated by the current activity. How do I do this?
private ChildEventListener pendingListener;
private ChildEventListener matchesListener;
private ChildEventListener alertListener;
private ValueEventListener flightListener;
private ValueEventListener prefsListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logout();
}
});
}
private void logout(){
if(pendingListener != null){
System.out.println(TAG +" pending listener removed");
mFirebaseRef
.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_PENDING).removeEventListener(pendingListener);
}
if(matchesListener != null){
System.out.println(TAG +" accept listener removed");
mFirebaseRef
.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_MATCHES).removeEventListener(matchesListener);
}
if(flightListener != null){
System.out.println(TAG + " flight listener removed");
mFirebaseRef
.child(FirebaseReference.CHILD_FLIGHTS)
.child(CURRENT_USER.getId()).removeEventListener(flightListener);
}
if(alertListener != null){
System.out.println(TAG + " alert listener removed");
mFirebaseRef.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_ALERTS).removeEventListener(alertListener);
}
if(prefsListener != null){
System.out.println(TAG + " prefsListener removed");
mFirebaseRef.child(FirebaseReference.CHILD_USERS)
.child(CURRENT_USER.getId())
.child(FirebaseReference.CHILD_PREFS).removeEventListener(prefsListener);
}
if(this.mAuthData != null){
mFirebaseRef.removeAuthStateListener(mAuthStateListener);
System.out.println(TAG + " authState listener removed");
}
// After logout, go to main activity
Intent intent = new Intent(MainScreen.this, loginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
The app crashes at .setOnClickListener. bLogout's id is defined in another layout, not main_screen
How to call Activity1 logout() function from Activity2
Create a Broadcast Receiver which call logout():
public class YourBroadcastReceiver extends BroadcastReceiver {
//local variables
private Context mContext;
public YourBroadcastReceiver(Context mContext){
this.mContext = mContext;
}
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals("LOGOUT")) {
((YourActivity) mContext).logout();
}
}
}
Register BroadcastReceiver in Activity 1:
public mYourBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//........
//Create an Intent Filter
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("LOGOUT");
mYourBroadcastReceiver = new YourBroadcastReceiver(this);
//Register receiver
registerReceiver(mYourBroadcastReceiver, intentFilter);
//.........
}
#Override
protected void onDestroy() {
super.onDestroy();
if (EcologDriverAIDApplication.DEBUG) {
Log.i(TAG, "onDestroy");
}
//Unregister receiver before destroy activity
unregisterReceiver(mYourBroadcastReceiver);
mYourBroadcastReceiver = null;
}
Broadcast logout:
final Intent intent = new Intent("LOGOUT");
sendBroadcast(intent);
Hope helps
Upon further research, this was simply solved by making logout public and writing the following for the onClickListener for bLogout in my fragment
//call logout in MainScreen
((MainScreen)getActivity()).logout();
I have created an app that forwards selected call to a number. However, right now, all call are forwarded to the number. What is missing in my code which does not allow specific callers to be forwarded. Thanks
java class
public class CallForwarding extends Activity {
private SharedPreferences prefs;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_forwarding);
final Switch switch1 = (Switch) findViewById(R.id.switch1);
editText = (EditText) findViewById(R.id.editText1);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
editText.setText(prefs.getString("edittext_content", ""));
switch1.setChecked(false);
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if(editText.getText().toString().trim().length() <= 7){
switch1.setChecked(false);
Toast.makeText(getApplicationContext(), "Please enter a number for receiving forwarded calls",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Call Forwarding is activated",Toast.LENGTH_SHORT).show();
callforward("*21*" + editText.getText().toString() + "#" ); // 0123456789 is the number you want to forward the calls.;
}
}else{
Toast.makeText(getApplicationContext(), "Call Forwarding is deactivated",Toast.LENGTH_SHORT).show();
callforward("#21#");
}
}
});}
#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, menu);
return true;
}
public void onPause(){
super.onPause();
prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editText = (EditText)findViewById(R.id.editText1);
editor.putString("edittext_content", editText.getText().toString());
editor.commit();
}
public void manage_numbers_onClick(View view) {
Intent myIntent = new Intent(this, Set_numbers_to_forward.class);
startActivity(myIntent);
}
private void callforward(String ArrayString)
{
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager)
this.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Intent intentCallForward = new Intent(Intent.ACTION_CALL);
Uri mmiCode = Uri.fromParts("tel", ArrayString, "#");
intentCallForward.setData(mmiCode);
startActivity(intentCallForward);
}
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(s.equals(TelephonyManager.EXTRA_STATE_RINGING)){
String incomingnumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
incomingnumber.contentEquals(incomingnumber);
}
}
private class PhoneCallListener extends PhoneStateListener
{ private Context mContext;
private boolean isPhoneCalling = false;
DBAdapter db = new DBAdapter(mContext);
#Override
public void onCallStateChanged(int state, String incomingnumber)
{
//phone ringing
if (TelephonyManager.CALL_STATE_RINGING == state)
{
String contacts = db.getAllContacts().toString();
if(incomingnumber == contacts) {
callforward("*21*" + editText.getText().toString() + "#" );
} else if(incomingnumber != contacts){
//do nothing
callforward("#21#");
}
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state)
{
// active
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state)
{
// run when class initial and phone call ended, need detect flag
// from CALL_STATE_OFFHOOK
if (isPhoneCalling)
{
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
}
This question already has answers here:
How to make a phone call in android and come back to my activity when the call is done?
(21 answers)
Closed 9 years ago.
I try here to make a phone call and it works but the problem is when i finish the call,i don't get my view back.it stay stack in the calls list...and when i click on the button return in my phone it goes back to my activity that i want to show...Thanks :)
#Override
public void onClick(View arg0) {
if (arg0 == btn_ajout) {
Intent i=new Intent(Docteur_gestion.this, AjoutDocActivity.class);
startActivity(i);
}
if(arg0 == btn_appel) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+global_txt_tel_doc));
startActivity(callIntent);
}
}
You need to implement a phoneStateListener as follows:
public class MainActivity extends Activity {
final Context context = this;
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonCall);
// add PhoneStateListener
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
// add button listener
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));
startActivity(callIntent);
}
});
}
//monitor phone call activities
private class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
String LOG_TAG = "LOGGING 123";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
Log.i(LOG_TAG, "OFFHOOK");
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended,
// need detect flag from CALL_STATE_OFFHOOK
Log.i(LOG_TAG, "IDLE");
if (isPhoneCalling) {
Log.i(LOG_TAG, "restart app");
// restart app
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
}
Two permissions required in the manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
and
<uses-permission android:name="android.permission.CALL_PHONE" />
I found this solution on this link
I have two files.
IntentServiceTest1Activity.java
public class IntentServiceTest1Activity extends Activity {
/** Called when the activity is first created. */
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.mamlambo.intent.action.MESSAGE_PROCESSED";#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.txt_result);
String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
result.setText(text);
}
}
private ResponseReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText input = (EditText) findViewById(R.id.txt_input);
String strInputMsg = input.getText().toString();
Intent msgIntent = new Intent(IntentServiceTest1Activity.this, SimpleIntentService.class);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_MSG, strInputMsg);
startService(msgIntent);
}
});
}
}
SimpleIntentService.java
public class SimpleIntentService extends IntentService {
public static final String PARAM_IN_MSG = "imsg";
public static final String PARAM_OUT_MSG = "omsg";
public SimpleIntentService()
{
super("SimpleIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String msg = intent.getStringExtra(PARAM_IN_MSG);
SystemClock.sleep(30000); // 30 seconds
String resultTxt = msg + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);
sendBroadcast(broadcastIntent);
}
}
Via Log.d(), I can see the onHandleIntent was never called even though the service was started. My Log.d trail goes after startService(msgIntent); and stops there. No Log.d from within onHandleIntent was displayed. What is wrong? And what can I do to make it work?
Thanks!
I solved mine by adding onStartCommand but not overriding it.
public int onStartCommand(Intent intent, int flags, int startId) //sometimes overriding onStartCommand will not call onHandleIntent
{
Logger_.logtoFile(tag, "here..!", 1);
return super.onStartCommand(intent,flags,startId);
}