Android Oreo允许应用程序读取来自运营商的USSD消息。

利用emoney执行话费充值,需要执行USSD代码,尝试编写apk执行ussd代码进行充值。

尝试在Android8的系统上进行USSD session交互,发现暂时没有解决方案。。。。

尝试一次性发送所有USSD,*123*1*5*1256#,发现如果到了需要输入类似密码之类的自定义字符串时,会失败。

只能发送第一个USSD代码,无法进行后续的菜单交互。如果只需要调用USSD获取话费余额、套餐情况的请拿走。

代码如下:

package com.zongh.dbussd;

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 android.support.design.widget.Snackbar;
import android.support.annotation.RequiresApi; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; 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();
}
}
}
<?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>

USSD 杂记的更多相关文章

  1. [Erlang 0118] Erlang 杂记 V

       我在知乎回答问题不多,这个问题: "对你职业生涯帮助最大的习惯是什么?它是如何帮助你的?",我还是主动回答了一下.    做笔记 一开始笔记软件做的不好的时候就发邮件给自己, ...

  2. Ubuntu杂记——Ubuntu下用虚拟机共享上网

    由于最近把自己电脑环境换成了Ubuntu,但学校的网络是电信的闪讯,大学里用过的人都知道这货有多坑,而且没有Linux客户端,上网都是问题,怪不得国内用Linux的人那么少,特别是高校的学生(让我瞎逼 ...

  3. 一个ubuntu phper的自我修养(杂记)

    ubuntu使用杂记 1.flatabulous安装使用. flatabulous是一个ubuntu图标主题. 使用它,必须得安装tweak插件. sudo add-apt-repository pp ...

  4. 有关Java的日期处理的一些杂记

    在企业应用开发中,经常会遇到日期的相关处理,说实话JDK自带的日期方法很难用.就我个人而言我一般都会采用joda-time来替代JDK自身的日期. 这篇文章是杂记,所以写的比较零散,希望大家不要见怪. ...

  5. 分布式系统之CAP理论杂记[转]

    分布式系统之CAP理论杂记 http://www.cnblogs.com/highriver/archive/2011/09/15/2176833.html 分布式系统的CAP理论: 理论首先把分布式 ...

  6. Redis杂记

    参考资料: Redis 教程 | 菜鸟教程 : http://www.runoob.com/redis/redis-tutorial.html Redis快速入门 :http://www.yiibai ...

  7. MySQL杂记

    参考资料: w3school  SQL 教程 : http://www.w3school.com.cn/sql/index.asp 21分钟 MySQL 入门教程 : http://www.cnblo ...

  8. Android之开发杂记(一)

    1.cygwin环境变量设置 可在Cygwin.bat 中设置 set NDK_ROOT=P:/android/android-ndk-r8e 或者在home\Administrator\.bash_ ...

  9. ios程序开发杂记

    ios程序开发杂记 一.程序构建 与一般的程序构建无太大区别,都是源文件编译链接这一套,通常是在mac上做交叉编译,也就是利用xcode里带的ios编译工具集去生成arm架构的ios程序(或是x86的 ...

随机推荐

  1. div里包含img底部多出3px的解决办法

    如果将一个img放在div里面,你会发现在img下面无端端的就多出3px的空白出来.padding.margin.border都设为0,无效!那么怎么解决这个问题呢? 问题图: 解决后的效果: 这个B ...

  2. [SQL]LeetCode196. 删除重复的电子邮箱 | Delete Duplicate Emails

    Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique ...

  3. Java Runtime.exec()的使用

    Sun的doc里其实说明还有其他的用法: exec(String[] cmdarray, String[] envp, File dir) Executes the specified command ...

  4. Typescript 查缺补漏

    Types Casting: let input = xxx as HTMLInputElement; let input = <HTMLElement>xxxx; Object Shap ...

  5. SH2018笔试题之成长值问题

    一.题目 详见代码 二.代码 import java.util.Scanner; /** * 3 * 1 1 5 10 * 2 3 4 * 1 4 6 -5 */ public class main4 ...

  6. 【FairyGUI & Unity】实现血条UI扣血与加血的缓动效果

    组件设计 创建一个进度条组件,作为血条. bar是实际血量条 DownBar是扣血缓动背景图层 UpBar是加血缓动背景图层 LowBar是低血量变色(和控制器配合,本文不讲) n11组合是血量参考线 ...

  7. Android Studio升级到3.1.4后打开旧项目警告:The `android.dexOptions.incremental` property is deprecated and it has no effect on the build process.

    现象截图 问题原因&解决方案 在build.gralde中,对Android开发过程中突破的方法数的限制,做了如下解决配置: dexOptions { incremental true jav ...

  8. Spring Boot分布式系统实践【1】-架构设计

    前言 [第一次尝试去写一个系列,肯定会有想不到的地方,欢迎大家留言指正] 本系列将介绍如果从零构建一套分布式系统.同时也是对自己过去工作的一个梳理过程. 本文先整理出构建系统的主要技术选型,以及技术框 ...

  9. C++STL模板库关联容器之set/multiset

    目录 一丶关联容器简介.set/multiset 二丶演示代码. 一丶关联容器简介.set/multiset 我们的序列容器,底层都是线性表构成的. 比如 vector list deque. 关联容 ...

  10. ES6躬行记(18)——迭代器

    ES6将迭代器和生成器内置到语言中,不仅简化了数据处理和集合操作,还弥补了for.while等普通循环的不足,例如难以遍历无穷集合或自定义的树结构等. 迭代器(Iterator)是一种用于迭代的对象, ...