안드로이드에서 전화를 걸고 통화가 끝나면 내 활동으로 돌아 오는 방법은 무엇입니까?
전화를 걸기위한 활동을 시작하고 있지만 '통화 종료'버튼을 눌렀을 때 내 활동으로 돌아 가지 않습니다. '통화 종료'버튼을 눌렀을 때 되돌아 오는 통화 활동을 시작하려면 어떻게해야합니까? 이것이 내가 전화하는 방법입니다.
String url = "tel:3334444";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
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"/>
이것은 스타터가 묻는 질문에 관한 것입니다.
코드의 문제는 숫자를 제대로 전달하지 못한다는 것입니다.
코드는 다음과 같아야합니다.
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
가 사용됩니다.
우리는 같은 문제가 있었고 PhoneStateListener
호출이 끝나는 시간을 식별하기 위해 a 를 사용하여 문제를 해결할 수 있었지만 finish()
다시 시작하기 전에 원래 활동을 수행해야했습니다 startActivity
. 그렇지 않으면 호출 로그가 앞에 있습니다.
EndCallListener가 가장 기능적인 예라는 것을 발견했습니다. (finish (), call, restart) 설명 된 동작을 얻기 위해 몇 가지 SharedPreferences를 추가하여 리스너가이 동작을 관리하기위한 참조를 갖도록했습니다.
내 OnClick, 초기화 및 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 번호와 동일하지 않은 경우).
:)
startActivityForResult ()를 사용할 수 있습니다
이것은 내 관점에서 해결책입니다.
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);
}
물론 활동 (클래스) 정의에서는 View.OnClickListener 구현해야합니다.
예를 들어, 먼저 사용자가 전화를 걸고 자하는 번호를 쓴 다음 통화 버튼을 누르고 전화로 연결됩니다. 통화 취소 후 사용자는 응용 프로그램으로 다시 전송됩니다. 이를 위해서는 버튼에 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" />
@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);
}
리스너를 사용하려는 경우 매니페스트에도이 권한을 추가해야합니다.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
호출이 끝난 후 내부 PhoneStateListener가 더 잘 사용됩니다.
Intent intent = new Intent(CallDispatcherActivity.this, CallDispatcherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
여기서 CallDispatcherActivity는 사용자가 전화 서비스를 시작한 활동입니다 (필자의 경우 택시 서비스 발송자에게). 이것은 안드로이드 전화 앱을 상단에서 제거하기 때문에 사용자는 내가 본 못생긴 코드 대신 돌아옵니다.
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.
Perfect tutorial here! Always check this blog because it has many excellent tutorials!
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" />
Try using:
finish();
at the end of activity. It will redirect you to your previous activity.
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.
// 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>
@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.
Add this is your xml: android:autoLink="phone"
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
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent .setData(Uri.parse("tel:+91-XXXXXXXXX"));
startActivity(callIntent );
for more reference click here http://androiddhina.blogspot.in/2015/10/how-to-make-phone-call-from-android.html
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.
'Programming' 카테고리의 다른 글
Flink와 Storm의 주요 차이점은 무엇입니까? (0) | 2020.07.03 |
---|---|
코 틀린의 자원 활용 (0) | 2020.07.03 |
GitHub 프로젝트와 이정표의 차이점 / 관계는 무엇입니까? (0) | 2020.07.02 |
전달 된 인수가 Bash의 파일 또는 디렉토리인지 확인하십시오. (0) | 2020.07.02 |
파이썬에서 사전을 반복 할 때 왜 .iteritems ()를 호출해야합니까? (0) | 2020.07.02 |