如何在 Android 中拨打电话并在通话结束后返回到我的活动?

发布于 2024-10-13 15:12:58 字数 224 浏览 8 评论 0原文

我正在启动一项活动来拨打电话,但是当我按下“结束通话”按钮时,它不会返回到我的活动。您能告诉我如何启动一个通话活动,当按下“结束通话”按钮时该活动会返回给我吗?这就是我打电话的方式:

    String url = "tel:3334444";
    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));

I am launching an activity to make a phone call, but when I pressed the 'end call' button, it does not go back to my activity. Can you please tell me how can I launch a call activity which comes back to me when 'End call' button is pressed? This is how I'm making the phone call:

    String url = "tel:3334444";
    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

悍妇囚夫 2024-10-20 15:12:58

使用 PhoneStateListener 查看通话何时结束。您很可能需要触发侦听器操作以等待呼叫开始(等到再次从 PHONE_STATE_OFFHOOK 更改为 PHONE_STATE_IDLE),然后编写一些代码以使您的应用程序恢复到 IDLE 状态。

您可能需要在服务中运行侦听器以确保其保持运行并重新启动您的应用程序。一些示例代码:

EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

监听器定义:

private class EndCallListener extends PhoneStateListener {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        if(TelephonyManager.CALL_STATE_RINGING == state) {
            Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
        }
        if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
            //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
            Log.i(LOG_TAG, "OFFHOOK");
        }
        if(TelephonyManager.CALL_STATE_IDLE == state) {
            //when this state occurs, and your flag is set, restart your app
            Log.i(LOG_TAG, "IDLE");
        }
    }
}

在您的 Manifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

use a PhoneStateListener to see when the call is ended. you will most likely need to trigger the listener actions to wait for a the call to start (wait until changed from PHONE_STATE_OFFHOOK to PHONE_STATE_IDLE again) and then write some code to bring your app back up on the IDLE state.

you may need to run the listener in a service to ensure it stays up and your app is restarted. some example code:

EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

Listener definition:

private class EndCallListener extends PhoneStateListener {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        if(TelephonyManager.CALL_STATE_RINGING == state) {
            Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
        }
        if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
            //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
            Log.i(LOG_TAG, "OFFHOOK");
        }
        if(TelephonyManager.CALL_STATE_IDLE == state) {
            //when this state occurs, and your flag is set, restart your app
            Log.i(LOG_TAG, "IDLE");
        }
    }
}

In your Manifest.xml file add the following permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
汹涌人海 2024-10-20 15:12:58

这是关于Starter提出的问题。

您的代码的问题是您没有正确传递号码。

代码应该是:

private OnClickListener next = new OnClickListener() {

     public void onClick(View v) {
        EditText num=(EditText)findViewById(R.id.EditText01); 
        String number = "tel:" + num.getText().toString().trim();
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(number)); 
        startActivity(callIntent);
    }
};

不要忘记在清单文件中添加权限。

<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>

<uses-permission android:name="android.permission.CALL_PRIVILEGED"></uses-permission>

在使用 DIAL 时拨打紧急电话号码。

This is regarding the question asked by Starter.

The problem with your code is that you are not passing the number properly.

The code should be:

private OnClickListener next = new OnClickListener() {

     public void onClick(View v) {
        EditText num=(EditText)findViewById(R.id.EditText01); 
        String number = "tel:" + num.getText().toString().trim();
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(number)); 
        startActivity(callIntent);
    }
};

Do not forget to add the permission in manifest file.

<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>

or

<uses-permission android:name="android.permission.CALL_PRIVILEGED"></uses-permission>

for emergency number in case DIAL is used.

如若梦似彩虹 2024-10-20 15:12:58

我们遇到了同样的问题,并设法通过使用 PhoneStateListener 来识别通话何时结束来解决该问题,但此外,我们还必须在再次启动之前 finish() 原始活动与 startActivity 一起使用,否则调用日志将位于其前面。

We had the same problem and managed to solve it by using a PhoneStateListener to identify when the call ends, but additionally we had to finish() the original activity before starting it again with startActivity, otherwise the call log would be in front of it.

北城挽邺 2024-10-20 15:12:58

我发现 EndCallListener 是最实用的示例,为了获取所描述的行为(finish()、调用、重新启动),我添加了一些 SharedPreferences,以便侦听器有一个引用来管理此行为。

我的 OnClick、initialise 和 EndCallListener 仅响应来自应用程序的调用。其他呼叫被忽略。

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class EndCallListener extends PhoneStateListener {

private String TAG ="EndCallListener";
private int     LAUNCHED = -1;

SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(
                                myActivity.mApp.getBaseContext());

SharedPreferences.Editor _ed = prefs.edit();

@Override
    public void onCallStateChanged(int state, String incomingNumber) {
    String _prefKey = myActivity.mApp                          
                      .getResources().getString(R.string.last_phone_call_state_key),
    _bPartyNumber = myActivity.mApp                           
                      .getResources().getString(R.string.last_phone_call_bparty_key);

    int mLastCallState = prefs.getInt(_prefKey, LAUNCHED);

    //Save current call sate for next call
    _ed.putInt(_prefKey,state);
    _ed.commit();

        if(TelephonyManager.CALL_STATE_RINGING == state) {
            Log.i(TAG, " >> RINGING, number: " + incomingNumber);
        }
        if(TelephonyManager.CALL_STATE_IDLE == state && mLastCallState != LAUNCHED ) {
            //when this state occurs, and your flag is set, restart your app

            if (incomingNumber.equals(_bPartyNumber) == true) {
                //Call relates to last app initiated call
            Intent  _startMyActivity =  
               myActivity.mApp                               
               .getPackageManager()                                  
               .getLaunchIntentForPackage(
                 myActivity.mApp.getResources()
                 .getString(R.string.figjam_package_path));

_startMyActivity.setAction(                                     
        myActivity.mApp.getResources()
        .getString(R.string.main_show_phone_call_list));

                myActivity.mApp
                        .startActivity(_startMyActivity);
                Log.i(TAG, "IDLE >> Starting MyActivity with intent");
            }
            else
                Log.i(TAG, "IDLE after calling "+incomingNumber);

        }

    }
}

将这些添加到 strings.xml

<string name="main_show_phone_call_list">android.intent.action.SHOW_PHONE_CALL_LIST</string>
<string name="last_phone_call_state_key">activityLpcsKey</string>
<string name="last_phone_call_bparty_key">activityLpbpKey</string>

以及清单中的类似内容,如果您需要返回到调用之前的外观

  <activity android:label="@string/app_name" android:name="com.myPackage.myActivity" 
      android:windowSoftInputMode="stateHidden"
        android:configChanges="keyboardHidden" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="android.intent.action.SHOW_PHONE_CALL_LIST" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
  </activity>

并将它们放入“myActivity”中,

public static Activity mApp=null; //Before onCreate()
  ...
onCreate( ... ) {
  ...
if (mApp == null) mApp = this; //Links your resources to other classes
  ...
    //Test if we've been called to show phone call list
    Intent _outcome = getIntent();
    String _phoneCallAction = mApp.getResources().getString(R.string.main_show_phone_call_list);
    String _reqAction = _outcome.getAction();//Can be null when no intent involved

         //Decide if we return to the Phone Call List view
         if (_reqAction != null &&_reqAction.equals(_phoneCallAction) == true) {
                         //DO something to return to look and feel
         }

  ...
        myListView.setOnItemClickListener(new OnItemClickListener() { //Act on item when selected
             @Override
             public void onItemClick(AdapterView<?> a, View v, int position, long id) {

                 myListView.moveToPosition(position);
                 String _bPartyNumber = "tel:"+myListView.getString(myListView.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

                 //Provide an initial state for the listener to access.
                 initialiseCallStatePreferences(_bPartyNumber);

                 //Setup the listener so we can restart myActivity
                    EndCallListener _callListener = new EndCallListener();
                    TelephonyManager _TM = (TelephonyManager)mApp.getSystemService(Context.TELEPHONY_SERVICE);

                    _TM.listen(_callListener, PhoneStateListener.LISTEN_CALL_STATE);

                         Intent _makeCall = new Intent(Intent.ACTION_CALL, Uri.parse(_bPartyNumber));

                 _makeCall.setComponent(new ComponentName("com.android.phone","com.android.phone.OutgoingCallBroadcaster"));
                    startActivity(_makeCall);                           
                finish();
              //Wait for call to enter the IDLE state and then we will be recalled by _callListener
              }
        });


}//end of onCreate()

请使用它来初始化 myActivity 中 onClick 的行为,例如在 onCreate() 之后

private void initialiseCallStatePreferences(String _BParty) {
    final int LAUNCHED = -1;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
                                mApp.getBaseContext());
    SharedPreferences.Editor _ed = prefs.edit();

    String _prefKey = mApp.getString(R.string.last_phone_call_state_key),
           _bPartyKey = mApp.getString(R.string.last_phone_call_bparty_key);

    //Save default call state before next call
        _ed.putInt(_prefKey,LAUNCHED);
        _ed.putString(_bPartyKey,_BParty);
        _ed.commit();

}

您应该发现,单击电话号码列表即可完成您的活动,拨打该号码并在通话结束时返回您的活动。

在应用程序仍在运行时从外部拨打电话不会重新启动您的活动(除非它与上次呼叫的 BParty 号码相同)。

:)

I found the EndCallListener the most functional example, to get the behaviour described (finish(), call, restart) I added a few SharedPreferences so the Listener had a reference to manage this behaviour.

My OnClick, initialise and EndCallListener only respond to calls from app. Other calls ignored.

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class EndCallListener extends PhoneStateListener {

private String TAG ="EndCallListener";
private int     LAUNCHED = -1;

SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(
                                myActivity.mApp.getBaseContext());

SharedPreferences.Editor _ed = prefs.edit();

@Override
    public void onCallStateChanged(int state, String incomingNumber) {
    String _prefKey = myActivity.mApp                          
                      .getResources().getString(R.string.last_phone_call_state_key),
    _bPartyNumber = myActivity.mApp                           
                      .getResources().getString(R.string.last_phone_call_bparty_key);

    int mLastCallState = prefs.getInt(_prefKey, LAUNCHED);

    //Save current call sate for next call
    _ed.putInt(_prefKey,state);
    _ed.commit();

        if(TelephonyManager.CALL_STATE_RINGING == state) {
            Log.i(TAG, " >> RINGING, number: " + incomingNumber);
        }
        if(TelephonyManager.CALL_STATE_IDLE == state && mLastCallState != LAUNCHED ) {
            //when this state occurs, and your flag is set, restart your app

            if (incomingNumber.equals(_bPartyNumber) == true) {
                //Call relates to last app initiated call
            Intent  _startMyActivity =  
               myActivity.mApp                               
               .getPackageManager()                                  
               .getLaunchIntentForPackage(
                 myActivity.mApp.getResources()
                 .getString(R.string.figjam_package_path));

_startMyActivity.setAction(                                     
        myActivity.mApp.getResources()
        .getString(R.string.main_show_phone_call_list));

                myActivity.mApp
                        .startActivity(_startMyActivity);
                Log.i(TAG, "IDLE >> Starting MyActivity with intent");
            }
            else
                Log.i(TAG, "IDLE after calling "+incomingNumber);

        }

    }
}

add these to strings.xml

<string name="main_show_phone_call_list">android.intent.action.SHOW_PHONE_CALL_LIST</string>
<string name="last_phone_call_state_key">activityLpcsKey</string>
<string name="last_phone_call_bparty_key">activityLpbpKey</string>

and something like this in your Manifest if you need to return to the look and feel before the call

  <activity android:label="@string/app_name" android:name="com.myPackage.myActivity" 
      android:windowSoftInputMode="stateHidden"
        android:configChanges="keyboardHidden" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="android.intent.action.SHOW_PHONE_CALL_LIST" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
  </activity>

and put these in your 'myActivity'

public static Activity mApp=null; //Before onCreate()
  ...
onCreate( ... ) {
  ...
if (mApp == null) mApp = this; //Links your resources to other classes
  ...
    //Test if we've been called to show phone call list
    Intent _outcome = getIntent();
    String _phoneCallAction = mApp.getResources().getString(R.string.main_show_phone_call_list);
    String _reqAction = _outcome.getAction();//Can be null when no intent involved

         //Decide if we return to the Phone Call List view
         if (_reqAction != null &&_reqAction.equals(_phoneCallAction) == true) {
                         //DO something to return to look and feel
         }

  ...
        myListView.setOnItemClickListener(new OnItemClickListener() { //Act on item when selected
             @Override
             public void onItemClick(AdapterView<?> a, View v, int position, long id) {

                 myListView.moveToPosition(position);
                 String _bPartyNumber = "tel:"+myListView.getString(myListView.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

                 //Provide an initial state for the listener to access.
                 initialiseCallStatePreferences(_bPartyNumber);

                 //Setup the listener so we can restart myActivity
                    EndCallListener _callListener = new EndCallListener();
                    TelephonyManager _TM = (TelephonyManager)mApp.getSystemService(Context.TELEPHONY_SERVICE);

                    _TM.listen(_callListener, PhoneStateListener.LISTEN_CALL_STATE);

                         Intent _makeCall = new Intent(Intent.ACTION_CALL, Uri.parse(_bPartyNumber));

                 _makeCall.setComponent(new ComponentName("com.android.phone","com.android.phone.OutgoingCallBroadcaster"));
                    startActivity(_makeCall);                           
                finish();
              //Wait for call to enter the IDLE state and then we will be recalled by _callListener
              }
        });


}//end of onCreate()

use this to initilaise the behaviour for your onClick in myActivity e.g. after onCreate()

private void initialiseCallStatePreferences(String _BParty) {
    final int LAUNCHED = -1;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
                                mApp.getBaseContext());
    SharedPreferences.Editor _ed = prefs.edit();

    String _prefKey = mApp.getString(R.string.last_phone_call_state_key),
           _bPartyKey = mApp.getString(R.string.last_phone_call_bparty_key);

    //Save default call state before next call
        _ed.putInt(_prefKey,LAUNCHED);
        _ed.putString(_bPartyKey,_BParty);
        _ed.commit();

}

You should find that clicking your list of phone numbers finishes your activty, makes the call to the number and returns to your activty when the call ends.

Making a call from outside your app while it's still around won't restart your activty (unless it's the same as the last BParty number called).

:)

ゝ偶尔ゞ 2024-10-20 15:12:58

您可以使用 startActivityForResult()

you can use startActivityForResult()

老子叫无熙 2024-10-20 15:12:58

从我的角度来看,这是解决方案:

ok.setOnClickListener(this);
@Override
public void onClick(View view) {
    if(view == ok){
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + num));
        activity.startActivity(intent);

    }

当然,在 Activity (类)定义中,您必须实现 View.OnClickListener 。

This is solution from my point of view:

ok.setOnClickListener(this);
@Override
public void onClick(View view) {
    if(view == ok){
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + num));
        activity.startActivity(intent);

    }

Of course in Activity (class) definition you have to implement View.OnClickListener .

隐诗 2024-10-20 15:12:58

这是我的示例,首先用户输入他/她想要拨打的号码,然后按通话按钮并被定向到电话。呼叫取消后,用户将被发送回应用程序。为此,按钮需要在 xml 中具有 onClick 方法(本例中为“makePhoneCall”)。您还需要在清单中注册权限。

清单

<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

活动

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class PhoneCall extends Activity {

    EditText phoneTo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_call);

        phoneTo = (EditText) findViewById(R.id.phoneNumber);

    }
    public void makePhoneCall(View view) {




        try {
            String number = phoneTo.getText().toString();
            Intent phoneIntent = new Intent(Intent.ACTION_CALL);
            phoneIntent.setData(Uri.parse("tel:"+ number));
            startActivity(phoneIntent);


        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(PhoneCall.this,
                    "Call failed, please try again later!", Toast.LENGTH_SHORT).show();
        }
    }

}

XML

 <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/phoneNumber"
        android:layout_marginTop="67dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Call"
        android:id="@+id/makePhoneCall"
        android:onClick="makePhoneCall"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

Here is my example, first the user gets to write in the number he/she wants to dial and then presses a call button and gets directed to the phone. After call cancelation the user gets sent back to the application. In order to this the button needs to have a onClick method ('makePhoneCall' in this example) in the xml. You also need to register the permission in the manifest.

Manifest

<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Activity

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class PhoneCall extends Activity {

    EditText phoneTo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_call);

        phoneTo = (EditText) findViewById(R.id.phoneNumber);

    }
    public void makePhoneCall(View view) {




        try {
            String number = phoneTo.getText().toString();
            Intent phoneIntent = new Intent(Intent.ACTION_CALL);
            phoneIntent.setData(Uri.parse("tel:"+ number));
            startActivity(phoneIntent);


        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(PhoneCall.this,
                    "Call failed, please try again later!", Toast.LENGTH_SHORT).show();
        }
    }

}

XML

 <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:id="@+id/phoneNumber"
        android:layout_marginTop="67dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Call"
        android:id="@+id/makePhoneCall"
        android:onClick="makePhoneCall"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
妄司 2024-10-20 15:12:58
@Override
public void onClick(View view) {
    Intent phoneIntent = new Intent(Intent.ACTION_CALL);
    phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    startActivity(phoneIntent);
}
@Override
public void onClick(View view) {
    Intent phoneIntent = new Intent(Intent.ACTION_CALL);
    phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    startActivity(phoneIntent);
}
霓裳挽歌倾城醉 2024-10-20 15:12:58

如果您要使用侦听器,您还需要将此权限添加到清单中。

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

If you are going to use a listener you will need to add this permission to the manifest as well.

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
寒冷纷飞旳雪 2024-10-20 15:12:58

在看到呼叫完成后,在 PhoneStateListener 内部更好地使用:

Intent intent = new Intent(CallDispatcherActivity.this, CallDispatcherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

其中 CallDispatcherActivity 是用户发起呼叫的活动(在我的例子中是打给出租车服务调度员)。这只是从顶部删除了 Android 电话应用程序,用户返回而不是我在这里看到的丑陋代码。

Inside PhoneStateListener after seeing the call is finished better use:

Intent intent = new Intent(CallDispatcherActivity.this, CallDispatcherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Where CallDispatcherActivity is the activity where the user has launched a call (to a taxi service dispatcher, in my case). This just removes Android telephony app from the top, the user gets back instead of ugly code I saw here.

带上头具痛哭 2024-10-20 15:12:58

要返回到您的Activity,您需要监听TelephonyStates。在该侦听器上,您可以发送Intent以在手机空闲时重新打开您的Activity

至少我会这么做。

To return to your Activity, you will need to listen to TelephonyStates. On that listener you can send an Intent to re-open your Activity once the phone is idle.

At least thats how I will do it.

霞映澄塘 2024-10-20 15:12:58
  Intent callIntent = new Intent(Intent.ACTION_CALL);  
  callIntent.setData(Uri.parse("tel:"+number));  
   startActivity(callIntent);   

 **Add permission :**

 <uses-permission android:name="android.permission.CALL_PHONE" />          
  Intent callIntent = new Intent(Intent.ACTION_CALL);  
  callIntent.setData(Uri.parse("tel:"+number));  
   startActivity(callIntent);   

 **Add permission :**

 <uses-permission android:name="android.permission.CALL_PHONE" />          
如梦亦如幻 2024-10-20 15:12:58

尝试

finish();

在活动结束时使用:。它会将您重定向到之前的活动。

Try using:

finish();

at the end of activity. It will redirect you to your previous activity.

ま柒月 2024-10-20 15:12:58

使用 PhoneStateListener 时,需要确保使用 PHONE_STATE_OFFHOOK 后面的 PHONE_STATE_IDLE 来触发通话后要执行的操作。如果触发发生在看到 PHONE_STATE_IDLE 时,您最终将在通话之前执行此操作。因为你会看到状态改变 PHONE_STATE_IDLE -> PHONE_STATE_OFFHOOK -> 电话状态PHONE_STATE_IDLE。

When PhoneStateListener is used, one need to make sure PHONE_STATE_IDLE following a PHONE_STATE_OFFHOOK is used to trigger the action to be done after the call. If the trigger happens upon seeing PHONE_STATE_IDLE, you will end up doing it before the call. Because you will see the state change PHONE_STATE_IDLE -> PHONE_STATE_OFFHOOK -> PHONE_STATE_IDLE.

心的位置 2024-10-20 15:12:58

// 在 setonclicklistener 中放置以下代码:

EditText et_number=(EditText)findViewById(R.id.id_of_edittext); 
String my_number = et_number.getText().toString().trim();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(my_number)); 
startActivity(callIntent);

// 在清单中授予调用权限:

<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>

// in setonclicklistener put this code:

EditText et_number=(EditText)findViewById(R.id.id_of_edittext); 
String my_number = et_number.getText().toString().trim();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(my_number)); 
startActivity(callIntent);

// give permission for call in manifest:

<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
嗼ふ静 2024-10-20 15:12:58

@Dmitri Novikov,FLAG_ACTIVITY_CLEAR_TOP 清除新实例之上的所有活动实例。因此,它可能会在完成该过程之前结束旧实例。

@Dmitri Novikov, FLAG_ACTIVITY_CLEAR_TOP clears any active instance on top of the new one. So, it may end the old instance before it completes the process.

指尖凝香 2024-10-20 15:12:58

添加这是您的 xml:android:autoLink="phone"

Add this is your xml: android:autoLink="phone"

伴梦长久 2024-10-20 15:12:58

步骤:

1)在Manifest.xml文件中添加所需的权限。

<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

2)创建电话状态变化的监听器。

public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
    if(TelephonyManager.CALL_STATE_RINGING == state) {
    }
    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
        //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
    }
    if(TelephonyManager.CALL_STATE_IDLE == state) {
        //when this state occurs, and your flag is set, restart your app
    Intent i = context.getPackageManager().getLaunchIntentForPackage(
                            context.getPackageName());
    //For resuming the application from the previous state
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Uncomment the following if you want to restart the application instead of bring to front.
    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(i);
    }
}
}

3) 在 OnCreate 中初始化侦听器

EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

,但如果您想恢复应用程序的最后状态或将其从返回堆栈中恢复,则替换 FLAG_ACTIVITY_CLEAR_TOP 和 FLAG_ACTIVITY_SINGLE_TOP

参考此答案

Steps:

1)Add the required permissions in the Manifest.xml file.

<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

2)Create a listener for the phone state changes.

public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
    if(TelephonyManager.CALL_STATE_RINGING == state) {
    }
    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
        //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
    }
    if(TelephonyManager.CALL_STATE_IDLE == state) {
        //when this state occurs, and your flag is set, restart your app
    Intent i = context.getPackageManager().getLaunchIntentForPackage(
                            context.getPackageName());
    //For resuming the application from the previous state
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Uncomment the following if you want to restart the application instead of bring to front.
    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(i);
    }
}
}

3)Initialize the listener in your OnCreate

EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP with FLAG_ACTIVITY_SINGLE_TOP

Reference this Answer

乖乖哒 2024-10-20 15:12:58
   Intent callIntent = new Intent(Intent.ACTION_CALL);
   callIntent .setData(Uri.parse("tel:+91-XXXXXXXXX"));
   startActivity(callIntent );
   Intent callIntent = new Intent(Intent.ACTION_CALL);
   callIntent .setData(Uri.parse("tel:+91-XXXXXXXXX"));
   startActivity(callIntent );
葬心 2024-10-20 15:12:58

开始通话时,看起来不错。

不过,Android 11+ 和更低版本在将应用程序置于最前面方面存在差异。

Android 10 或更低版本您需要启动一个新 Intent,Android 11+ 您只需使用 BringTaskToFront

在呼叫状态 IDLE 中:

if (Build.VERSION.SDK_INT >= 11) {
    ActivityManager am = (ActivityManager) activity.getSystemService(Activity.ACTIVITY_SERVICE);
    am.moveTaskToFront(MyActivity.MyActivityTaskId, ActivityManager.MOVE_TASK_WITH_HOME);
} else {
    Intent intent = new Intent(activity, MyActivity.class);
    activity.startActivity(intent);
}

我在进行呼叫时设置 MyActivity.MyActivityTaskId我的活动就像这样,如果这不起作用,请在您想要返回的页面的父活动页面上设置此变量。

MyActivity.MyActivityTaskId = this.getTaskId();

MyActivityTaskId 是我的活动类上的静态变量,

public static int MyActivityTaskId = 0;

我希望这对您有用。我使用上面的代码有点不同,我在接听电话后立即打开我的应用程序,以便用户可以看到呼叫者的详细信息。

我还在 AndroidManifest.xml 中设置了一些内容:

/*Dont really know if this makes a difference*/
<activity android:name="MyActivity" android:taskAffinity="" android:launchMode="singleTask" />

和权限:

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />

如果或当您遇到困难时,请提出问题。

When starting your call, it looks fine.

There is a difference between android 11+ and down in bringing your app to the front though.

Android 10 or less you need to start a new intent, android 11+ you simply use BringTaskToFront

In the call state IDLE:

if (Build.VERSION.SDK_INT >= 11) {
    ActivityManager am = (ActivityManager) activity.getSystemService(Activity.ACTIVITY_SERVICE);
    am.moveTaskToFront(MyActivity.MyActivityTaskId, ActivityManager.MOVE_TASK_WITH_HOME);
} else {
    Intent intent = new Intent(activity, MyActivity.class);
    activity.startActivity(intent);
}

I set the MyActivity.MyActivityTaskId when making the call on my activity like so, it this doesnt work, set this variable on the parent activity page of the page you want to get back to.

MyActivity.MyActivityTaskId = this.getTaskId();

MyActivityTaskId is a static variable on my activity class

public static int MyActivityTaskId = 0;

I hope this will work for you. I use the above code a bit differently, I open my app as soon as the call is answered sothat the user can see the details of the caller.

I have set some stuff in the AndroidManifest.xml as well:

/*Dont really know if this makes a difference*/
<activity android:name="MyActivity" android:taskAffinity="" android:launchMode="singleTask" />

and permissions:

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />

Please ask questions if or when you get stuck.

银河中√捞星星 2024-10-20 15:12:58

要从应用程序进行呼叫,请使用简单的呼叫意图,之后如果您想监听呼叫状态,请使用下面的代码

1] 在您的类中实现此功能 -

实现AudioManager.OnAudioFocusChangeListener

2] 使用重写方法添加以下代码

 AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); //公共静态最终字符串AUDIO_SERVICE =“音频”;
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    断言audioManager!= null;
    audioManager.requestAudioFocus(这,AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);

@覆盖
公共无效onAudioFocusChange(int focusChange){
        切换(焦点更改){
            案例 AudioManager.AUDIOFOCUS_LOSS: {
                //在这里你可以暂停正在播放的音频
                休息;
            }
            案例 AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: {
                 //在这里你可以暂停正在播放的音频
                休息;
            }
            案例 AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: {
                休息;
            }
            案例 AudioManager.AUDIOFOCUS_GAIN: {
                 //当您的通话结束后,您将返回到活动
               //在这里恢复你的音频
                休息;
            }
        }
    }

3]添加这个

@覆盖
公共无效onDestroy(){
audioManager.abandonAudioFocus(this);
}

To call from app use simple intent for call, after that if you want to listen the call status then use below code

1] implement this in your class -

implements AudioManager.OnAudioFocusChangeListener

2] Add below code with overridden method

    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); //public static final String AUDIO_SERVICE = "audio";
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    assert audioManager != null;
    audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);

@Override
public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_LOSS: {
                //here you can pause your playing audio
                break;
            }
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: {
                 //here you can pause your playing audio
                break;
            }
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: {
                break;
            }
            case AudioManager.AUDIOFOCUS_GAIN: {
                 //here you will return back to the activity when your call is finsihed
               //resume your audio here
                break;
            }
        }
    }

3]Add this

@Override
public void onDestroy() {
audioManager.abandonAudioFocus(this);
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文