USSD 杂记
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 杂记的更多相关文章
- [Erlang 0118] Erlang 杂记 V
我在知乎回答问题不多,这个问题: "对你职业生涯帮助最大的习惯是什么?它是如何帮助你的?",我还是主动回答了一下. 做笔记 一开始笔记软件做的不好的时候就发邮件给自己, ...
- Ubuntu杂记——Ubuntu下用虚拟机共享上网
由于最近把自己电脑环境换成了Ubuntu,但学校的网络是电信的闪讯,大学里用过的人都知道这货有多坑,而且没有Linux客户端,上网都是问题,怪不得国内用Linux的人那么少,特别是高校的学生(让我瞎逼 ...
- 一个ubuntu phper的自我修养(杂记)
ubuntu使用杂记 1.flatabulous安装使用. flatabulous是一个ubuntu图标主题. 使用它,必须得安装tweak插件. sudo add-apt-repository pp ...
- 有关Java的日期处理的一些杂记
在企业应用开发中,经常会遇到日期的相关处理,说实话JDK自带的日期方法很难用.就我个人而言我一般都会采用joda-time来替代JDK自身的日期. 这篇文章是杂记,所以写的比较零散,希望大家不要见怪. ...
- 分布式系统之CAP理论杂记[转]
分布式系统之CAP理论杂记 http://www.cnblogs.com/highriver/archive/2011/09/15/2176833.html 分布式系统的CAP理论: 理论首先把分布式 ...
- Redis杂记
参考资料: Redis 教程 | 菜鸟教程 : http://www.runoob.com/redis/redis-tutorial.html Redis快速入门 :http://www.yiibai ...
- MySQL杂记
参考资料: w3school SQL 教程 : http://www.w3school.com.cn/sql/index.asp 21分钟 MySQL 入门教程 : http://www.cnblo ...
- Android之开发杂记(一)
1.cygwin环境变量设置 可在Cygwin.bat 中设置 set NDK_ROOT=P:/android/android-ndk-r8e 或者在home\Administrator\.bash_ ...
- ios程序开发杂记
ios程序开发杂记 一.程序构建 与一般的程序构建无太大区别,都是源文件编译链接这一套,通常是在mac上做交叉编译,也就是利用xcode里带的ios编译工具集去生成arm架构的ios程序(或是x86的 ...
随机推荐
- OJ002
register:这个关键字请求编译器尽可能的将变量存在CPU内部寄存器中,而不是通过内存寻址访问,以提高效率.注意是尽可能,不是绝对. 因为,如果定义了很多register变量,可能会超过CPU的寄 ...
- Three.js学习笔记04--纹理
1 纹理由图片组成 3D世界的纹理由图片组成. 将纹理以一定的规则映射到几何体上,一般是三角形上,那么这个几何体就有纹理皮肤了. 首先应该有一个纹理类,其次是有一个加载图片的方法,将这张图片和这个纹 ...
- C#的几种文件操作方法
创建或覆盖文件 需求:如果文件不存在,创建之,如果存在,覆盖之. 1,可能有问题的方法 using (FileStream fs = File.OpenWrite(@"d:\work\1.t ...
- [Swift]LeetCode223. 矩形面积 | Rectangle Area
Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined b ...
- [Swift]LeetCode763. 划分字母区间 | Partition Labels
A string S of lowercase letters is given. We want to partition this string into as many parts as pos ...
- Redis 设计与实现 (四)--事件、客户端
事件 一.文件事件 文件事件处理器使用I/O多路复用程序来同时监听多个套接字, 监听套接字,分配对应的处理事件. 四个组成部分:套接字 .I/O多路复用 . 文件事件分派器 . 事件处理器 连接应答处 ...
- 如何解决http请求返回结果中文乱码
如何解决http请求返回结果中文乱码 1.问题描述 http请求中,请求的结果集中包含中文,最终以乱码展示. 2.问题的本质 乱码的本质是服务端返回的字符集编码与客户端的编码方式不一致. 场景的如服务 ...
- app自动化问题点整理
1.配置SDK环境发现adb无法生效: 解决方案: 这个问题一般就是你的环境变量没有配置好,很多同学比较容易出现的点就是win10系统的环境变量配置: 一定要注意打开path添加:%ANDROID_H ...
- 关于Python pandas模块输出每行中间省略号问题
关于Python数据分析中pandas模块在输出的时候,每行的中间会有省略号出现,和行与行中间的省略号....问题,其他的站点(百度)中的大部分都是瞎写,根本就是复制黏贴以前的版本,你要想知道其他问题 ...
- 一个 Vue & Node 的全栈小项目
约学 - 可以寻找一起自习的小伙伴的Web APP 一个基于 Vue & Node 的移动端全栈小项目 在线演示(请使用移动端查看效果) 源码地址: https://github.com/G- ...