簡體   English   中英

如何在 Android 4.1 中以編程方式接聽/結束通話?

[英]How to programmatically answer/end a call in Android 4.1?

我正在編寫一個 android 應用程序,我需要在其中接聽來電,做一些工作,然后結束通話。 在所有谷歌搜索之后,我可以找到兩種不同的方法來實現這一點,這兩種方法都不適用於最新版本的 Android,特別是在 4.1 之后,Jelly Bean。

I.) 在“android.intent.action.PHONE_STATE”的廣播接收器中使用 Java 反射訪問“com.android.internal.telephony.ITelephony”。 下面的示例代碼可以在數百篇相關文章中找到:

public class PhoneCallReceiver extends BroadcastReceiver {
 Context context = null;
 private static final String TAG = "Phone call";
 private ITelephony telephonyService;

@Override
 public void onReceive(Context context, Intent intent) {
  if (!intent.getAction().equals("android.intent.action.PHONE_STATE")) 
    return;

  Log.v(TAG, "Receving....");
  TelephonyManager telephony = (TelephonyManager) 
  context.getSystemService(Context.TELEPHONY_SERVICE);  
  try {
      Log.v(TAG, "Get getTeleService...");
      Class c = Class.forName(telephony.getClass().getName());
      Method m = c.getDeclaredMethod("getITelephony");
      m.setAccessible(true);
      telephonyService = (ITelephony) m.invoke(telephony);
      telephonyService.silenceRinger();
      Log.v(TAG, "Answering Call now...");
      telephonyService.answerRingingCall();
      Log.v(TAG, "Call answered...");
      //telephonyService.endCall();
  } catch (Exception e) {
   e.printStackTrace();
   Log.e(TAG,
           "FATAL ERROR: could not connect to telephony subsystem");
   Log.e(TAG, "Exception object: " + e);
  }
 }
}

這段代碼的問題在於

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

需要此方法才能工作,並且此權限已從 android v 2.3 定義為“僅適用於系統應用程序”。 簡而言之,普通用戶應用程序無法再在清單文件中定義此權限。

II.) 另一種方法是模擬推動耳機掛鈎,使 Android 接聽電話。 這是通過廣播“Intent.ACTION_MEDIA_BUTTON”來完成的,如下面的代碼所示。

public class PhoneCallReceiver extends BroadcastReceiver {
 Context context = null;
 private static final String TAG = "Phone call";

 @Override
 public void onReceive(Context context, Intent intent) {
     if (!intent.getAction().equals("android.intent.action.PHONE_STATE")) 
         return;

     String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
     if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
         String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

         Intent answer = new Intent(Intent.ACTION_MEDIA_BUTTON);
         answer.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
         context.sendOrderedBroadcast(answer, null);
         Log.d(TAG, "Answered incoming call from: " + number);
     }   
     return;
 } 
}

此方法適用於 Android 4.1,之后 android 已限制用戶應用程序廣播“Intent.ACTION_MEDIA_BUTTON”。

所以我的結論是,目前我們無法在 Android 4.1 或更高版本中實現這一點。

有沒有其他人找到這個問題的任何其他解決方案或解決方法?

這適用於 Android 2.2 到 4.0,現在在將 try catch 添加到最后一行后,它適用於 4.1.2 和 4.2 坦率地說不知道它是如何工作的,但它對我有用。

Log.d(tag, "InSecond Method Ans Call");
// froyo and beyond trigger on buttonUp instead of buttonDown
Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");

Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
headSetUnPluggedintent.putExtra("state", 0);
headSetUnPluggedintent.putExtra("name", "Headset");
try {
    sendOrderedBroadcast(headSetUnPluggedintent, null);
} catch (Exception e) { 
    e.printStackTrace();
}

這在 Android 4.1.2 中對我有用,並且我已經在 4.2 上測試過這仍然給出了一個處理的異常。

編輯結束呼叫

希望這可以幫助所有尋找接聽和結束通話的整體解決方案的人。

/**
 * Reject button click listener will reject the incoming call.
 */
private class RejectCallOnClickListener implements OnClickListener {
    @Override
    public void onClick(View v) {
        Log.d(tag, "OnRejectButton: " + "Reject OnClick");
        ignoreCall();
        exitCleanly();
    }
}

/**
 * ignore incoming calls
 */
private void ignoreCall() {
    if (USE_ITELEPHONY)
        ignoreCallAidl();
    else
        ignoreCallPackageRestart();
}
/**
 * AIDL/ITelephony technique for ignoring calls
 */
private void ignoreCallAidl() {
    try {
        // telephonyService.silenceRinger();

        telephonyService.endCall();
    } catch (RemoteException e) {
        e.printStackTrace();
        Log.d(tag, "ignoreCall: " + "Error: " + e.getMessage());

    } catch (Exception e) {
        e.printStackTrace();
        Log.d(tag, "ignoreCall" + "Error: " + e.getMessage());

    }
}
/**
 * package restart technique for ignoring calls
 */
private void ignoreCallPackageRestart() {
    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    am.restartPackage("com.android.providers.telephony");
    am.restartPackage("com.android.phone");
}
/**
 * cleanup and exit routine
 */
private void exitCleanly() {
    unHookReceiver();
    this.finish();

}

我的應用程序已經使用以下代碼接聽電話大約 6 個月:

Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
            KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(i, null);

我已經在 2.2 到 4.2.2 的 Android 版本上對此進行了測試。 我在測試 4.2.2 設備時沒有看到 SecurityException 廣播“Intent.ACTION_MEDIA_BUTTON”,也沒有看到來自 Play 商店的崩潰報告表明發生了此類異常。

我會說這並不總是有效。 它在 HTC 設備上不起作用,因為 HTC 設備有一個 HeadsetObeserver,可以監聽有線耳機的實際插入。 如果沒有此事件,它當前是第三方應用程序廣播的 SecurityException,則 HeadsetHook KeyEvent 將被忽略。

之前的回答有誤導性。 下面的代碼塊什么都不做:

Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
headSetUnPluggedintent.putExtra("state", 0);
headSetUnPluggedintent.putExtra("name", "Headset");
try {
    sendOrderedBroadcast(headSetUnPluggedintent, null);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

除了生成一個 SecurityException 並捕獲它。

在代碼工作的其他答案中,這是因為 KeyEvent.KEYCODE_HEADSETHOOK 正在廣播。

嘗試使用此答案以編程方式結束通話。 它對我來說工作正常。

try {

    String serviceManagerName = "android.os.ServiceManager";
    String serviceManagerNativeName = "android.os.ServiceManagerNative";
    String telephonyName = "com.android.internal.telephony.ITelephony";

    Class telephonyClass;
    Class telephonyStubClass;
    Class serviceManagerClass;
    Class serviceManagerStubClass;
    Class serviceManagerNativeClass;
    Class serviceManagerNativeStubClass;

    Method telephonyCall;
    Method telephonyEndCall;
    Method telephonyAnswerCall;
    Method getDefault;

    Method[] temps;
    Constructor[] serviceManagerConstructor;

    // Method getService;
    Object telephonyObject;
    Object serviceManagerObject;

    telephonyClass = Class.forName(telephonyName);
    telephonyStubClass = telephonyClass.getClasses()[0];
    serviceManagerClass = Class.forName(serviceManagerName);
    serviceManagerNativeClass = Class.forName(serviceManagerNativeName);

    Method getService = // getDefaults[29];
            serviceManagerClass.getMethod("getService", String.class);

    Method tempInterfaceMethod = serviceManagerNativeClass.getMethod(
            "asInterface", IBinder.class);

    Binder tmpBinder = new Binder();
    tmpBinder.attachInterface(null, "fake");

    serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
    IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");
    Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);

    telephonyObject = serviceMethod.invoke(null, retbinder);
    //telephonyCall = telephonyClass.getMethod("call", String.class);
    telephonyEndCall = telephonyClass.getMethod("endCall");
    //telephonyAnswerCall = telephonyClass.getMethod("answerRingingCall");

    telephonyEndCall.invoke(telephonyObject);

} catch (Exception e) {
    e.printStackTrace();
    Log.error(DialerActivity.this,
            "FATAL ERROR: could not connect to telephony subsystem");
    Log.error(DialerActivity.this, "Exception object: " + e);
}

作為該線程的結論,這里是適用於我的 Android 4.2.2 代碼。

--> 呼叫通過模擬推入耳機掛鈎並將廣播保持在 try-catch 中,如上面線程中@PravinDodia 所述。 (觀察異常被拋出並在 catch 中處理,無論如何調用都會被應答。所以我想我們可以忽略這個異常並繼續生活,就好像什么都沒發生一樣!)

--> 使用 ITelephony 斷開呼叫。

public class PhoneCallReceiver extends BroadcastReceiver {
 Context context = null;
 private static final String TAG = "Phone call";

 @Override
 public void onReceive(Context context, Intent intent) {
     if (!intent.getAction().equals("android.intent.action.PHONE_STATE")) 
         return;
     else {
         String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

         if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
             answerPhoneHeadsethook(context, intent);
             return;
         }
         else if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
             Log.d(TAG, "CALL ANSWERED NOW!!");
             try {
                    synchronized(this) {
                        Log.d(TAG, "Waiting for 10 sec ");
                        this.wait(10000);
                    }
                }
                catch(Exception e) {
                    Log.d(TAG, "Exception while waiting !!");
                    e.printStackTrace();
                }
             disconnectPhoneItelephony(context);
             return;
         }
         else {
             Log.d(TAG, "ALL DONE ...... !!");
         }
     }  
 }

 public void answerPhoneHeadsethook(Context context, Intent intent) {
     String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
     if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
         String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
         Log.d(TAG, "Incoming call from: " + number);
         Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);             
         buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
         try {
             context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
             Log.d(TAG, "ACTION_MEDIA_BUTTON broadcasted...");
         }
         catch (Exception e) {
             Log.d(TAG, "Catch block of ACTION_MEDIA_BUTTON broadcast !");
         }

         Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
         headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
         headSetUnPluggedintent.putExtra("state", 1); // 0 = unplugged  1 = Headset with microphone 2 = Headset without microphone
         headSetUnPluggedintent.putExtra("name", "Headset");
         // TODO: Should we require a permission?
         try {
             context.sendOrderedBroadcast(headSetUnPluggedintent, null);
             Log.d(TAG, "ACTION_HEADSET_PLUG broadcasted ...");
         }
         catch (Exception e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                Log.d(TAG, "Catch block of ACTION_HEADSET_PLUG broadcast");
                Log.d(TAG, "Call Answered From Catch Block !!");
         }
         Log.d(TAG, "Answered incoming call from: " + number);  
    }
    Log.d(TAG, "Call Answered using headsethook");
 }

 public static void disconnectPhoneItelephony(Context context) {
     ITelephony telephonyService;
     Log.v(TAG, "Now disconnecting using ITelephony....");
      TelephonyManager telephony = (TelephonyManager) 
      context.getSystemService(Context.TELEPHONY_SERVICE);  
      try {
          Log.v(TAG, "Get getTeleService...");
          Class c = Class.forName(telephony.getClass().getName());
          Method m = c.getDeclaredMethod("getITelephony");
          m.setAccessible(true);
          telephonyService = (ITelephony) m.invoke(telephony);
          //telephonyService.silenceRinger();
          Log.v(TAG, "Disconnecting Call now...");
          //telephonyService.answerRingingCall();
          //telephonyService.endcall();
          Log.v(TAG, "Call disconnected...");
          telephonyService.endCall();
      } catch (Exception e) {
       e.printStackTrace();
       Log.e(TAG,
               "FATAL ERROR: could not connect to telephony subsystem");
       Log.e(TAG, "Exception object: " + e);
      }
 }
}

至少斷開功能是有效的,我們知道它是如何工作的。 所以那些想要開發呼叫限制應用程序的人可以繼續。 對於像我這樣想接聽電話的人,我想我們現在可以使用它,只希望它在下一個版本中不會停止工作。

試試這個 :

Intent 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 buttonDown
Intent 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");

AndroidManifest.xml文件中添加權限為

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

ITelephony 方法在 4.4 上不起作用,我發現耳機/媒體按鈕方法在掛斷前仍然允許相當長的響鈴。

這篇 chaps 博客文章展示了一種我在 4.4.2 Galaxy s4 和 HTC one mini 上測試過的新方法,它掛斷得更快,而且你也不會收到未接來電條目。

http://aprogrammersday.blogspot.co.uk/2014/05/disconnect-block-drop-calls-android-4.html

該技術使用如下運行時 exec,顯然您可能需要為某些設備使用不同的數字。

public class HangupPhoneCallReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (TelephonyManager.EXTRA_STATE_RINGING.equals(intent.getStringExtra(TelephonyManager.EXTRA_STATE))) {

            Executor eS = Executors.newSingleThreadExecutor();
            eS.execute(new Runnable() {
                @Override
                public void run() {
                    Runtime runtime = Runtime.getRuntime();
                    try {
                        Log.d(TAG, "service call phone 5 \n");
                        runtime.exec("service call phone 5 \n");
                    } catch (Exception exc) {
                        Log.e(TAG, exc.getMessage());
                    }
                }
            });

            return;
        }
    }
}

使用 IT 電話斷開呼叫在某些設備(如 Samsung S Duos)上不起作用。 但是你仍然可以讓鈴聲靜音:)

要結束舊版本然后 9.0 的調用,請使用以下命令:

TelephonyManager tm = (TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);

Method m1 = null;
try {
    m1 = tm.getClass().getDeclaredMethod("getITelephony");
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}
m1.setAccessible(true);
Object iTelephony = null;
try {
    iTelephony = m1.invoke(tm);
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}

Method m3 = null;
try {
    m3 = iTelephony.getClass().getDeclaredMethod("endCall");
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

try {
    m3.invoke(iTelephony);
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}
    

& 餡餅

TelecomManager telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
if (telecomManager != null) {
    return telecomManager.endCall();
}

Make sure your compile SDK version is 28
private void PhoneControl(int nControl) {
    if(nControl == PHONE_END_CALL) { // End call, all Android version
        try {
            TelecomManager telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
            if (telecomManager != null) {
                telecomManager.endCall();
            }
        }catch (Exception e) {}
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if(tm == null)
                return;
            tm.getClass().getMethod("endCall").invoke(tm);
            bIsEnding = true;
        } catch (Exception e) {


            /* Do Nothing */ }
    }

    if(nControl == PHONE_ACCEPT_CALL) { // Accept phone call
//      if(!bCallAccepted) { // Call déjà accepté => pas d'action (évite double action)
            bCallAccepted = true;
            if(Build.VERSION.SDK_INT >= 26) { // Pris en charge Android >= 8.0
                if(context.checkSelfPermission("android.permission.ANSWER_PHONE_CALLS") == PackageManager.PERMISSION_GRANTED) {
                    TelecomManager tm = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
                    if(tm != null)
                        tm.acceptRingingCall();
                }
            }
            if(Build.VERSION.SDK_INT >= 23 && Build.VERSION.SDK_INT < 26) { // Hangup in Android 6.x and 7.x
                MediaSessionManager mediaSessionManager =  (MediaSessionManager) context.getSystemService(Context.MEDIA_SESSION_SERVICE);
                if(mediaSessionManager != null) {
                    try {
                        List<MediaController> mediaControllerList = mediaSessionManager.getActiveSessions
                                (new ComponentName(context, NotificationReceiverService.class));

                        for (MediaController m : mediaControllerList) {
                            if ("com.android.server.telecom".equals(m.getPackageName())) {
                                m.dispatchMediaButtonEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
                                m.dispatchMediaButtonEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
                                break;
                            }
                        }
                    } catch (Exception e) {
//                      Toast.makeText(instance, "sdfsdf123123"+e, Toast.LENGTH_LONG).show();
                        Intent answerCalintent = new Intent(context, AcceptCallActivity.class);
                        answerCalintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                                Intent.FLAG_ACTIVITY_CLEAR_TASK  |
                                Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        context.startActivity(answerCalintent);
                        /* Do Nothing */ }
                }


//                new Thread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        try {
//                            Runtime.getRuntime().exec("input keyevent " +
//                                     Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
//                        } catch (IOException e) {
//                             // Runtime.exec(String) had an I/O problem, try to fall back
//                             String enforcedPerm = "android.permission.CALL_PRIVILEGED";
//                             Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
//                             Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN,
//                                      KeyEvent.KEYCODE_HEADSETHOOK));
//                             Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
//                                        Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
//                                        KeyEvent.KEYCODE_HEADSETHOOK));
//
//                             context.sendOrderedBroadcast(btnDown, enforcedPerm);
//                             context.sendOrderedBroadcast(btnUp, enforcedPerm);
//                         }
//                     }
//
//                  }).start();
            }
            if(Build.VERSION.SDK_INT < 23) { // Prend en charge jusqu'à Android 5.1
                try {
                    if(Build.MANUFACTURER.equalsIgnoreCase("HTC")) { // Uniquement pour HTC
                        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                        if(audioManager!=null && !audioManager.isWiredHeadsetOn()) {
                            Intent i = new Intent(Intent.ACTION_HEADSET_PLUG);
                            i.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
                            i.putExtra("state", 0);
                            i.putExtra("name", "Orasi");
                            try {
                                context.sendOrderedBroadcast(i, null);
                            } catch (Exception e) { /* Do Nothing */ }
                        }
                    }
                    Runtime.getRuntime().exec("input keyevent " +
                            Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
                } catch (Exception e) {
                    // Runtime.exec(String) had an I/O problem, try to fall back
                    String enforcedPerm = "android.permission.CALL_PRIVILEGED";
                    Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
                            Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN,
                                    KeyEvent.KEYCODE_HEADSETHOOK));
                    Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
                            Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
                                    KeyEvent.KEYCODE_HEADSETHOOK));

                    context.sendOrderedBroadcast(btnDown, enforcedPerm);
                    context.sendOrderedBroadcast(btnUp, enforcedPerm);
                }
            }
//       }
    }
}
    
<!--Incoming call state Listen-->
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <!--    Store Data in Device/Shared pref-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!--Get Incoming Number-->
    <uses-permission android:name="android.permission.READ_CALL_LOG" />

    <!--Answer call-->
    <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission
        android:name="android.permission.MODIFY_PHONE_STATE"
        tools:ignore="ProtectedPermissions" />


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

    public class NotificationReceiverService extends NotificationListenerService {
        public NotificationReceiverService() {
        }
    }

<service
    android:name=".notifications.NotificationReceiverService"
    android:enabled="true"
    android:exported="true"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">

    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>


if(Build.VERSION.SDK_INT >= 26) { // Permission necessaire
    if(checkSelfPermission("android.permission.ANSWER_PHONE_CALLS") != PackageManager.PERMISSION_GRANTED) {
        String szPermissions[] = {"android.permission.ANSWER_PHONE_CALLS"};
        requestPermissions(szPermissions, 0);
    }
}
if(Build.VERSION.SDK_INT < 26 && Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1 )
{ // Permission pour Android 6.x et 7.x
    ContentResolver contentResolver = getContentResolver();
    String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
    String packageName = getPackageName();
    if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)) {
        Intent intent2 = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
            intent2 = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
        }
        startActivity(intent2);


        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 100ms
                Intent intent=new Intent(MainActivity.this, Main2Activity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

            }
        }, 1000);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM