Android calls automatically

Source: Internet
Author: User

The Android system provides telephone-related interfaces for calling, such as obtaining the phone status and mobile phone service, as well as obtaining the phone status. Therefore, you can perform different operations based on the phone status.

This example mainly analyzes a code for automatically answering incoming calls. The code is written by someone else and learned together:

To listen to the phone status, the general practice is to write a broadcast receiver to listen to the phone status change, the configuration file is as follows:

        <receiver android:name=".AutoAnswerReceiver" android:enabled="true">        <intent-filter>        <action android:name="android.intent.action.PHONE_STATE" />        </intent-filter>        </receiver>

At this time, if the phone status changes, such as incoming calls, you can enter the Code. The Code is as follows:

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.database.Cursor;import android.media.AudioManager;import android.net.Uri;import android.preference.PreferenceManager;import android.provider.ContactsContract.PhoneLookup;import android.telephony.TelephonyManager;public class AutoAnswerReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// Load preferencesSharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);// Check phone stateString phone_state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);if (phone_state.equals(TelephonyManager.EXTRA_STATE_RINGING) && prefs.getBoolean("enabled", false)) {// Check for "second call" restrictionif (prefs.getBoolean("no_second_call", false)) {AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);if (am.getMode() == AudioManager.MODE_IN_CALL) {return;}}// Check for contact restrictionsString which_contacts = prefs.getString("which_contacts", "all");if (!which_contacts.equals("all")) {int is_starred = isStarred(context, number);if (which_contacts.equals("contacts") && is_starred < 0) {return;}else if (which_contacts.equals("starred") && is_starred < 1) {return;}}// Call a service, since this could take a few secondscontext.startService(new Intent(context, AutoAnswerIntentService.class));}}// returns -1 if not in contact list, 0 if not starred, 1 if starredprivate int isStarred(Context context, String number) {int starred = -1;Cursor c = context.getContentResolver().query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),new String[] {PhoneLookup.STARRED},null, null, null);if (c != null) {if (c.moveToFirst()) {starred = c.getInt(0);}c.close();}return starred;}}

For the moment, no other code is needed, because other code mainly determines the setting options separately. If the phone status changes, the automatic answering service is started, that is, context. startservice (new intent (context, autoanswerintentservice. class ));

In this way, the Automatic Answer service is started. In this code, the logic of Bluetooth to answer the phone is also introduced as follows:

The Code is as follows:

protected void onHandleIntent(Intent intent) {Context context = getBaseContext();// Load preferencesSharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);BluetoothHeadset bh = null;if (prefs.getBoolean("headset_only", false)) {bh = new BluetoothHeadset(this, null);}// Let the phone ring for a set delaytry {Thread.sleep(Integer.parseInt(prefs.getString("delay", "2")) * 1000);} catch (InterruptedException e) {// We don't really care}// Check headset status right before picking up the callif (prefs.getBoolean("headset_only", false) && bh != null) {if (bh.getState() != BluetoothHeadset.STATE_CONNECTED) {bh.close();return;}bh.close();}// Make sure the phone is still ringingTelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);if (tm.getCallState() != TelephonyManager.CALL_STATE_RINGING) {return;}// Answer the phonetry {answerPhoneAidl(context);}catch (Exception e) {e.printStackTrace();Log.d("AutoAnswer","Error trying to answer using telephony service.  Falling back to headset.");answerPhoneHeadsethook(context);}// Enable the speakerphoneif (prefs.getBoolean("use_speakerphone", false)) {enableSpeakerPhone(context);}return;}

First, determine whether to set the Bluetooth headset to answer the phone. If not, use the normal method to answer the phone. Of course, make sure that the phone is still ringing at this time, because sometimes the phone may only ring. Then, the system automatically receives the call. For details, see answerphoneaidl (context). The Code for answering the call is as follows:

// Answer the phonetry {answerPhoneAidl(context);}catch (Exception e) {e.printStackTrace();Log.d("AutoAnswer","Error trying to answer using telephony service.  Falling back to headset.");answerPhoneHeadsethook(context);}

First, use the general aidl method to answer the call. If an exception occurs, simulate a button to answer the call. For the two codes, see:

private void answerPhoneHeadsethook(Context context) {// Simulate a press of the headset button to pick up the callIntent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");// froyo and beyond trigger on buttonUp instead of buttonDownIntent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");}@SuppressWarnings("unchecked")private void answerPhoneAidl(Context context) throws Exception {// Set up communication with the telephony service (thanks to Tedd's Droid Tools!)TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);Class c = Class.forName(tm.getClass().getName());Method m = c.getDeclaredMethod("getITelephony");m.setAccessible(true);ITelephony telephonyService;telephonyService = (ITelephony)m.invoke(tm);// Silence the ringer and answer the call!telephonyService.silenceRinger();telephonyService.answerRingingCall();}

Generally, the above Code can answer the phone. Maybe on some mobile phones, if the Framework Code implementation is changed, it may be unable to be connected and needs to be modified.

The setting options mentioned at the beginning of this article are the application startup interface, which is written in preferenceactivity. For details, see:

Public class autoanswerpreferenceactivity extends preferenceactivity implements onsharedpreferencechangelistener

Then load the XML file. You can set many option parameters.

For the running interface, see:

In addition, there is a startup class in this example. For the configuration file, see:

        <receiver android:name=".AutoAnswerBootReceiver" android:enabled="true">        <intent-filter>        <action android:name="android.intent.action.BOOT_COMPLETED" />        </intent-filter>        </receiver>

You can set notification to notify users.

public void onReceive(Context context, Intent intent) {AutoAnswerNotifier notifier = new AutoAnswerNotifier(context);notifier.updateNotification();}

Autoanswernotifier can be used to set a prompt or cancel the prompt:

private void enableNotification() {// Intent to call to turn off AutoAnswerIntent notificationIntent = new Intent(mContext, AutoAnswerPreferenceActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);// Create the notificationNotification n = new Notification(R.drawable.stat_sys_autoanswer, null, 0);n.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;n.setLatestEventInfo(mContext, mContext.getString(R.string.notification_title), mContext.getString(R.string.notification_text), pendingIntent);mNotificationManager.notify(NOTIFICATION_ID, n);}private void disableNotification() {mNotificationManager.cancel(NOTIFICATION_ID);}

Finally, do not forget to add permissions because the operation phone number and other related services require the relevant permissions:

<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /><uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /><uses-permission android:name="android.permission.READ_CONTACTS" /><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

This sample code will be uploaded for download and learning. The link is as follows:
Http://download.csdn.net/detail/bawang_cn/5031509

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.