交互式ussd会话(多步)不适用于Android 8(奥利奥)

时间:2017-10-02 05:26:36

标签: android ussd android-8.0-oreo

我目前正在使用android api level 26(Nexus 6P)中提供的Telephony Manager(USSD响应)。对于单步ussd会话,它正在工作。

参考: java 8 bug

示例:

USSD请求:“A”(ussd session initiates)

USSD回复:“X”(ussd会话终止)

    TelephonyManager =  telephonyManager(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    Handler handler = new Handler();
    TelephonyManager.UssdResponseCallback callback = new TelephonyManager.UssdResponseCallback() {
        @Override
        public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
            super.onReceiveUssdResponse(telephonyManager, request, response);
            Log.e("ussd",response.toString());

        }

        @Override
        public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, String request, int failureCode) {
            super.onReceiveUssdResponseFailed(telephonyManager, request, failureCode);
            Log.e("ussd","failed with code " + Integer.toString(failureCode));
        }
    };

    try {
           Log.e("ussd","trying to send ussd request");
           telephonyManager.sendUssdRequest("*123#",
                    callback,
                    handler);
        }catch (Exception e){


            String msg= e.getMessage();
            Log.e("DEBUG",e.toString());
            e.printStackTrace();
        }

但是对于交互式ussd请求 - 响应(多步),它不起作用。  多步骤场景如下:

步骤#1。

USSD请求:“A”(ussd session initiates)

USSD回复:“X”

步骤#2。

USSD请求:“B”(ussd session继续)

USSD回复:“Y”

第3步。

USSD请求:“C”

USSD回复:“Z”(ussd会话终止)

5 个答案:

答案 0 :(得分:2)

我能够获得一个菜单,并通过发送一个号码来回复它,但除此之外,我想这是电信公司的摆布-他们发送了一个菜单,该菜单会阻塞整个屏幕,如果您取消它,则整个会话都会消亡。在电信行业工作过之后,我认为这对电信公司而言可能有所不同,因为其中一些网关具有可以杀死用户发起的会话并将其替换为电信端发起的会话的网关。从技术上讲,这两个会话是分离的。但是这是我的代码:

    package org.rootio.test.telephony.telephonyautorespond;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import androidx.annotation.RequiresApi;

import static android.content.ContentValues.TAG;

interface UssdResultNotifiable {
    void notifyUssdResult(String request, String returnMessage, int resultCode);
}

public class HomeActivity extends Activity implements UssdResultNotifiable {

    USSDSessionHandler hdl;
    private TelephonyManager telephonyManager;
    private PhoneCallListener listener;
    private TelecomManager telecomManager;

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

    public void onUssdSend(View view) {
        //USSDHandler callback = new USSDHandler(view);
        /* if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
         *//*if(ActivityCompat.shouldShowRequestPermissionRationale(HomeActivity.this, Manifest.permission.CALL_PHONE))
                    {

                    }
                    else
                    {*//*
                        //ActivityCompat.requestPermissions(HomeActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 0);
                   // }
                    Snackbar.make(view, "permissions were missing", Snackbar.LENGTH_LONG)
                            .setAction("Response", null).show();
                    return;
                }*/
        //HomeActivity.this.telephonyManager.sendUssdRequest("*#123*99#", callback, new Handler());



        hdl = new USSDSessionHandler(HomeActivity.this, HomeActivity.this);

        hdl.doSession(((EditText)this.findViewById(R.id.ussdText)).getText().toString());

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void toggleListener(View v) {
        if (((Switch) v).isChecked()) {
            this.listenForTelephony();
            Toast.makeText(this, "Listening for calls", Toast.LENGTH_LONG).show();
        } else {
            this.stopListeningForTelephony();
        }
    }

    private void listenForTelephony() {
        this.telephonyManager = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
        this.telecomManager = (TelecomManager) this.getSystemService(this.TELECOM_SERVICE);
        this.listener = new PhoneCallListener();
        telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    private void stopListeningForTelephony() {
        this.telephonyManager = null;
        this.telecomManager = null;
    }

    @Override
    public void notifyUssdResult(final String request, final String returnMessage, final int resultCode) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(HomeActivity.this, "Request was " + request + "\n response is " + returnMessage + "\n result code is " + resultCode, Toast.LENGTH_LONG).show();

            }
        });

    }


    class PhoneCallListener extends PhoneStateListener {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    HomeActivity.this.telecomManager.acceptRingingCall();
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    Toast.makeText(HomeActivity.this, "Call is no longer active...", Toast.LENGTH_LONG);
                    break;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    class USSDHandler extends TelephonyManager.UssdResponseCallback {

        View parent;

        USSDHandler(View v) {
            this.parent = v;
        }

        @Override
        public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
            super.onReceiveUssdResponse(telephonyManager, request, response);
            Snackbar.make(this.parent, response, Snackbar.LENGTH_LONG)
                    .setAction("Response", null).show();
        }

        @Override
        public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, String request, int failureCode) {
            super.onReceiveUssdResponseFailed(telephonyManager, request, failureCode);
            Snackbar.make(this.parent, "error is " + failureCode + " for req " + request, Snackbar.LENGTH_LONG)
                    .setAction("Response", null).show();
        }
    }


}

class USSDSessionHandler {

    TelephonyManager tm;
    private UssdResultNotifiable client;
    private Method handleUssdRequest;
    private Object iTelephony;

    USSDSessionHandler(Context parent, UssdResultNotifiable client) {
        this.client = client;
        this.tm = (TelephonyManager) parent.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            this.getUssdRequestMethod();
        } catch (Exception ex) {
            //log
        }

    }

    private void getUssdRequestMethod() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (tm != null) {
            Class telephonyManagerClass = Class.forName(tm.getClass().getName());
            if (telephonyManagerClass != null) {
                Method getITelephony = telephonyManagerClass.getDeclaredMethod("getITelephony");
                getITelephony.setAccessible(true);
                this.iTelephony = getITelephony.invoke(tm); // Get the internal ITelephony object
                Method[] methodList = iTelephony.getClass().getMethods();
                this.handleUssdRequest = null;
                /*
                 *  Somehow, the method wouldn't come up if I simply used:
                 *  iTelephony.getClass().getMethod('handleUssdRequest')
                 */

                for (Method _m : methodList)
                    if (_m.getName().equals("handleUssdRequest")) {
                        handleUssdRequest = _m;
                        break;
                    }
            }
        }
    }

    public void doSession(String ussdRequest) {
        try {

            if (handleUssdRequest != null) {
                handleUssdRequest.setAccessible(true);
                handleUssdRequest.invoke(iTelephony, SubscriptionManager.getDefaultSubscriptionId(), ussdRequest, new ResultReceiver(new Handler()) {

                    @Override
                    protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
                        /*
                         * Usually you should the getParcelable() response to some Parcel
                         * child class but that's not possible here, since the "UssdResponse"
                         * class isn't in the SDK so we need to
                         * reflect again to get the result of getReturnMessage() and
                         * finally return that!
                         */

                        Object p = ussdResponse.getParcelable("USSD_RESPONSE");

                        if (p != null) {

                            Method[] methodList = p.getClass().getMethods();
                            for(Method m : methodList)
                            {
                                Log.i(TAG, "onReceiveResult: " + m.getName());
                            }
                            try {
                                CharSequence returnMessage = (CharSequence) p.getClass().getMethod("getReturnMessage").invoke(p);
                                CharSequence request = (CharSequence) p.getClass().getMethod("getUssdRequest").invoke(p);
                                USSDSessionHandler.this.client.notifyUssdResult("" + request, "" + returnMessage, resultCode); //they could be null
                            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                });
            }
        } catch (IllegalAccessException | InvocationTargetException e1) {
            e1.printStackTrace();
        }
    }
}

请忽略呼叫应答内容-我在使用此应用之前在Oreo上测试自动呼叫应答。下面是显示的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".HomeActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="USSD Input"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/ussdText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName" />
    </LinearLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onUssdSend"
        android:text="send" />
</LinearLayout>

答案 1 :(得分:1)

我设法通过使用反射来绕过一些问题(例如多区段USSD响应不起作用)。我已经制作了一个GitHub要点here

显然,假设是,给出了正确的权限(此时只有CALL_PHONE) - 就上下文而言,我只在活动中运行过这个,但我认为它会正常工作在大多数情况下,如果不是全部/任何。

接下来就是弄清楚如何维持会话,如果可能的话。

答案 2 :(得分:0)

这些API无法正确处理基于菜单的USSD。它们的预期用例将用于查询简单的内容,例如分钟数或用户计划中剩余的数据。对于基于菜单的系统,需要有一些有关持续会话的概念,而API不支持这种会话。

答案 3 :(得分:0)

public class MainActivity extends AppCompatActivity {
private Button dail;
private String number;
private TelephonyManager telephonyManager;

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


    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    dail = (Button) findViewById(R.id.dail);
    dail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    runtimepermissions();
                    return;
                }else{
                    telephonyManager.sendUssdRequest("*121#", new TelephonyManager.UssdResponseCallback() {
                        @Override
                        public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
                            super.onReceiveUssdResponse(telephonyManager, request, response);

                            Log.d("Received response","okay");
                            ((TextView)findViewById(R.id.response)).setText(response);
                        }

                        @Override
                        public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, String request, int failureCode) {
                            super.onReceiveUssdResponseFailed(telephonyManager, request, failureCode);
                            Log.e("ERROR ","can't receive response"+failureCode);
                        }
                    },new Handler(Looper.getMainLooper()){
                        @Override
                        public void handleMessage(Message msg) {
                            Log.e("ERROR","error");
                        }
                    });
                }

        }
    });

    }
    public boolean runtimepermissions() {
        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE}, 100);
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                Log.d("PERMISSIONS","granted");
               // doJob();
            } else {
                runtimepermissions();
            }
        }

}

}

如果您使用双SIM卡,请确保更改要测试的网络(在我使用的是Airtel(* 121#)。

答案 4 :(得分:0)

不幸的是,Google在Oreo中添加的API仅适用于USSD服务,您可以在开始时拨打整个USSD代码并获取响应,而无需在会话中输入任何内容。他们显然没有意识到的是,大多数电信公司出于安全原因都阻止了此操作,尤其是在有PIN输入的情况下。 API的设计实际上似乎是为了处理进一步响应的情况,但是正如各种发布者指出的那样,甚至从Android 10起,它实际上也无法正常工作。

我的公司Hover开发了一个Android SDK,该SDK使用可访问性服务来运行多步USSD会话,并使其似乎在您的应用程序中发生。您可以为USSD服务创建配置,触发会话以从您的应用运行,并传入所需的任何运行时变量。用户永远不会看到USSD会话,并且在返回响应时会通知您的应用,您可以根据需要对其进行解析。它适用于Android 4.3及更高版本。

SDK是免费集成和使用的,直到您大规模使用为止。请参阅我们的docs开始使用。

(披露:我是Hover的CTO)