How can I stop calling with codes in android? - android

I have created an application that calls a number. It is working but I want to close the calling after 30 sec. How can I do that?
My code is:
MyTimer = new CountDownTimer(60000, 30000) {
public void onTick(long millisUntilFinished) {
intent.setData(Uri.parse("tel:" + num2 + ""));
startActivity(intent);
}
public void onFinish() {
}
}.start();

You'll need some Reflection for that. First, create this interface:
package com.android.internal.telephony;
public interface ITelephony {
boolean endCall();
void answerRingingCall();
void silenceRinger();
}
And end call with this:
private void endCall() {
TelephonyManager telephonyManager = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
Class<?> myClass = null;
try {
myClass = Class.forName(telephonyManager.getClass().getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method method = null;
try {
method = myClass.getDeclaredMethod("getITelephony");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
method.setAccessible(true);
ITelephony telephonyService = null;
try {
telephonyService = (ITelephony) method.invoke(telephonyManager);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
telephonyService.endCall();
}
Modified answer from here.
EDIT: Adding example:Add this to some button click
//Start call
makeCall(phoneNumber);
//wait several seconds
try {
long time = holdCallSeconds * 1000;
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
//hang up
endCall();
void makeCall(String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(phoneNumber));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
startActivity(intent);
}

Related

How to close system dialog or notification on OS version 7.0+?

I am developing android app and i want close system dialog programmatically.
I am using this code for closing system dialog, this code is working fine in android 6.0 and below versions but the problem is that it's not working in android 7.0 and android 8.0. How to solve this problem.
Please help me thanks advance.
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
If you want to close notification panel,
I am using below code for android Oreo.
Handler collapseNotificationHandler;
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d(tag, "window focus changed");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
collapseNow();
}
}
public void collapseNow() {
try {
// Initialize 'collapseNotificationHandler'
if (collapseNotificationHandler == null) {
collapseNotificationHandler = new Handler();
}
// Post a Runnable with some delay - currently set to 300 ms
collapseNotificationHandler.postDelayed(new Runnable() {
#Override
public void run() {
// Use reflection to trigger a method from 'StatusBarManager'
Object statusBarService = getSystemService("statusbar");
Class<?> statusBarManager = null;
try {
statusBarManager = Class.forName("android.app.StatusBarManager");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method collapseStatusBar = null;
try {
// Prior to API 17, the method to call is 'collapse()'
// API 17 onwards, the method to call is `collapsePanels()`
if (Build.VERSION.SDK_INT > 16) {
collapseStatusBar = statusBarManager.getMethod("collapsePanels");
} else {
collapseStatusBar = statusBarManager.getMethod("collapse");
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
collapseStatusBar.setAccessible(true);
try {
collapseStatusBar.invoke(statusBarService);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// Currently, the delay is 10 ms. You can change this
// value to suit your needs.
collapseNotificationHandler.postDelayed(this, 10L);
}
}, 10L);
} catch (Exception e) {
e.printStackTrace();
}
}

Number picker start changing value for few seconds

I would like a numberpicker to start changing the values automaticly for few seconds .
private void changeValueByOne(final NumberPicker higherPicker, final boolean increment) {
Method method;
try {
// refelction call for
// higherPicker.changeValueByOne(true);
method = higherPicker.getClass().getDeclaredMethod("changeValueByOne", boolean.class);
method.setAccessible(true);
method.invoke(higherPicker, increment);
} catch (final NoSuchMethodException e) {
e.printStackTrace();
} catch (final IllegalArgumentException e) {
e.printStackTrace();
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (final InvocationTargetException e) {
e.printStackTrace();
}
}
I ve implemented this method and tried
Thread thread = new Thread() {
#Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
changeValueByOne(wp,true);
}
});
}
};
thread.start();
But it is not ok .
I would like to have an effect as a slot machine .
Why can't you simply set the value to an incremented value? Something like this:
private void changeValueByOne(final NumberPicker higherPicker) {
int oldValue = higherPicker.getValue();
higherPicker.setValue(oldValue++);
}
EDIT
Here is the source of the method you're reflecting:
private void changeValueByOne(boolean increment) {
if (mHasSelectorWheel) {
mInputText.setVisibility(View.INVISIBLE);
if (!moveToFinalScrollerPosition(mFlingScroller)) {
moveToFinalScrollerPosition(mAdjustScroller);
}
mPreviousScrollerY = 0;
if (increment) {
mFlingScroller.startScroll(0, 0, 0, -mSelectorElementHeight, SNAP_SCROLL_DURATION);
} else {
mFlingScroller.startScroll(0, 0, 0, mSelectorElementHeight, SNAP_SCROLL_DURATION);
}
invalidate();
} else {
if (increment) {
setValueInternal(mValue + 1, true);
} else {
setValueInternal(mValue - 1, true);
}
}
}
You can see that if mHasSelectorWheel = true, it calls the startScroll method. In other words, it sounds like your NumberPicker has mHasSelectorWheel = false, in which case you're out of luck given your current implementation. It is highly advisable that you look into a custom scrollable number picker widget.

AudioRecorder App crashes when I record a second time

My app breaks down when I attempt to record a second a time when I hit the stop button. I went through this code several times. I can't find the problem. I'm not sure if its my MediaRecorder or my MediaPlayer. It works the first time around. But not the second time. can anyone find the problem.
public class PatientName extends Activity implements OnClickListener {
private Button instructionsBtn;
private ImageView record;
private ImageView stop;
private MediaPlayer instructions;
private MediaPlayer namePlayer;
private MediaRecorder nameRecorder;
private String OUTPUT_FILE;
private Button play;
private Button accept;
private LinearLayout review;
private Button delete;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_name);
OUTPUT_FILE = Environment.getExternalStorageDirectory() + "/namerecording.3gpp";
initializeViews();
initializeListeners();
}
public void initializeViews() {
instructionsBtn = (Button)findViewById(R.id.patient_name_instructions);
record = (ImageView)findViewById(R.id.record_name);
stop = (ImageView)findViewById(R.id.stop_name);
stop.setVisibility(View.GONE);
play = (Button)findViewById(R.id.play_name);
play.setVisibility(View.GONE);
review = (LinearLayout)findViewById(R.id.review_name);
delete = (Button)findViewById(R.id.delete_name);
accept = (Button)findViewById(R.id.accept_name);
review.setVisibility(View.GONE);
}
public void initializeListeners() {
instructionsBtn.setOnClickListener(this);
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
delete.setOnClickListener(this);
accept.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
public void playInstructions() {
setMaxVolume();
instructions = MediaPlayer.create(PatientName.this, R.raw.intro_instructions);
instructions.start();
instructions.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
instructions.release();
instructionsBtn.setEnabled(true);
}
});
}
public void setMaxVolume() {
AudioManager audio = (AudioManager) getSystemService(this.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
}
public void onClick(View v) {
int id = v.getId();
if (id==R.id.patient_name_instructions) {
instructionsBtn.setEnabled(false);
playInstructions();
}
if (id==R.id.record_name) {
beginRecording();
}
if (id==R.id.stop_name){
play.setVisibility(View.VISIBLE);
nameRecorder.stop();
}
if (id==R.id.play_name) {
playbackRecording();
}
if (id==R.id.delete_name){
deleteRecording();
}
if (id==R.id.accept_name) {
saveAndContinue();
}
}
private void beginRecording(){
record.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}else {
nameRecorder = new MediaRecorder();
nameRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
nameRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
nameRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
nameRecorder.setOutputFile(OUTPUT_FILE);
try {
nameRecorder.prepare();
} catch (IllegalStateException e) {
Toast toast = Toast.makeText(this,"Illegal State",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(this,"Error Recording",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
nameRecorder.start();
}
}
private void playbackRecording() {
play.setVisibility(View.GONE);
namePlayer = new MediaPlayer();
try {
namePlayer.setDataSource(OUTPUT_FILE);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
namePlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
namePlayer.start();
namePlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
namePlayer.release();
nameRecorder.release();
review.setVisibility(View.VISIBLE);
}
});
}
private void deleteRecording() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private void saveAndContinue() {
Intent intent = new Intent(PatientName.this, PatientLocation.class);
startActivity(intent);
}
}
Here is my logCat:
I figured out the issue. In the beginRecording method, I have an if and else statement that handles the output file. Unfortunately, the code that I had in the else statement was something that I wanted to always run no matter what.

Change the Wifi Direct name in android

I want change the device name in Wifi direct....So far i have tried
try {
Method m = wpm.getClass().getMethod(
"setDeviceName",
new Class[] { WifiP2pManager.Channel.class, String.class,
WifiP2pManager.ActionListener.class });
m.invoke(WifiP2pManager wifimngr,WifiP2pManager.Channel wifichannel, new_name, new WifiP2pManager.ActionListener() {
public void onSuccess() {
//Code for Success in changing name
}
public void onFailure(int reason) {
//Code to be done while name change Fails
}
});
} catch (Exception e) {
e.printStackTrace();
}
But it doesn't work for me.....Is there any idea how can I achieve this goal?
Have a look at https://github.com/spawrks/WifiDirectNameChanger I have tested it on a wiko darkfull it's work
Changing WifiDirect Name - Android Java
This is what worked for me, anyhow I don't recommend using reflection to access hidden APIs in the WifiP2pManager.
Worked Android OS: 5.1.1
public void setDeviceName(String devName) {
try {
Class[] paramTypes = new Class[3];
paramTypes[0] = WifiP2pManager.Channel.class;
paramTypes[1] = String.class;
paramTypes[2] = WifiP2pManager.ActionListener.class;
Method setDeviceName = manager.getClass().getMethod("setDeviceName", paramTypes);
setDeviceName.setAccessible(true);
Object arglist[] = new Object[3];
arglist[0] = channel;
arglist[1] = devName;
arglist[2] = new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
updateLog("setDeviceName: onSuccess");
}
#Override
public void onFailure(int reason) {
updateLog("setDeviceName: onSuccess");
}
};
setDeviceName.invoke(manager, arglist);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
Refer: https://gist.github.com/aslamanver/39aa668b3073bc4f52aeb09b5a7ea3be

Android pairing bluetooth devices without dialog with pin

I want pairing my android cellphone and SPP bluetooth without dialog with pin and confirmation. I have this code, register BroadcastReceiver:
IntentFilter filter = new IntentFilter(ACTION_PAIRING_REQUEST);
registerReceiver(mPairReceiver, filter);
pairDevice(device);
pairDevice method:
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastReceiver:
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_PAIRING_REQUEST.equals(action)) {
System.out.println("ACTION_PAIRING_REQUEST");
setBluetoothPairingPin(device);
}
}
};
setBluetoothPairingPin method:
public void setBluetoothPairingPin(BluetoothDevice device)
{
byte[] pinBytes = convertPinToBytes("0000");
try {
Log.d(TAG, "Try to set the PIN");
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, pinBytes);
Log.d(TAG, "Success to add the PIN.");
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, false);
Log.d(TAG, "Success to setPairingConfirmation.");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
but always show dialog with pin and confirmation.

Categories

Resources