activity、service、BroadcastReceive之间如何互相通讯,并取回相 android broadcast

直接贴代码吧

activity代码:

package cn.com.sgcc.eshop.ui.activity.smscheck;

import android.app.Activity;

import android.content.ComponentName;

import android.content.Context;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.Handler;

import android.os.IBinder;

import android.os.Message;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

import cn.com.sgcc.eshop.R;

import cn.com.sgcc.eshop.model.smscheck.SmsCheck;

import cn.com.sgcc.eshop.service.smscheck.SmsService;

import cn.com.sgcc.eshop.service.smscheck.SmsService.LocalBinder;

import cn.com.sgcc.eshop.transfer.TransferResult;

import cn.com.sgcc.eshop.transfer.TransferStatus;

import cn.com.sgcc.eshop.transfer.smscheck.SmsCheckExcutor;

public class SmsCheckActivity extends Activity {

private SmsCheckExcutor smsCheckExcutor;

private String phoneNum;

private String senderNum;

private String verifyCode;

private String id;

boolean mBound = false;

private SmsService mService;

private Handler smsHandler = new Handler() {

@Override

public void handleMessage(final Message msg) {

Bundle bundle = msg.getData();

senderNum = bundle.getString("senderNum");

verifyCode = bundle.getString("verifyCode");

EditText text = (EditText)findViewById(R.id.verifyCode);

text.setText(verifyCode);

//EditText phoneNumText = (EditText)findViewById(R.id.phoneNum);

//phoneNumText.setText(senderNum);

}

};

/** 定交ServiceConnection,用于绑定Service的 */

private ServiceConnection mConnection = new ServiceConnection() {

@Override

public void onServiceConnected(ComponentName className, IBinder service) {

// 已经绑定了SmsService,强转IBinder对象,调用方法得到SmsService对象

LocalBinder binder = (LocalBinder) service;

mService = binder.getService();

mBound = true;

}

@Override

public void onServiceDisconnected(ComponentName arg0) {

mBound = false;

}

};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.smscheck_activity);

initBean();

}

@Override

protected void onStart() {

super.onStart();

// 绑定Service,绑定后就会调用mConnetion里的onServiceConnected方法

Intent intent = new Intent(this, SmsService.class);

bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

activity、service、BroadcastReceive之间如何互相通讯,并取回相 android broadcast
}

@Override

protected void onStop() {

super.onStop();

// 解绑Service,这样可以节约内存

if (mBound) {

unbindService(mConnection);

mBound = false;

}

}

private class smsLoadThread extends Thread{

@Override

public void run() {

while((verifyCode==null || verifyCode.equals(""))||(senderNum==null ||senderNum.equals(""))){

if(mBound){

senderNum = mService.getSenderNum();

verifyCode = mService.getVerifyCode();

}

}

Message msg = new Message();

Bundle bundle = new Bundle();

bundle.putString("senderNum", senderNum);

bundle.putString("verifyCode", verifyCode);

msg.setData(bundle);

smsHandler.sendMessage(msg);

}

}

public void getVerifyCode(View view) {

EditText phoneNumText = (EditText) findViewById(R.id.phoneNum);

// 得到手机号码

phoneNum = phoneNumText.getText() == null ? "" : phoneNumText.getText()

.toString();

if (phoneNum == null || phoneNum.equals("")) {

Toast.makeText(SmsCheckActivity.this, R.string.phoneNum,

Toast.LENGTH_LONG).show();

return;

}

TransferResult result = new TransferResult();

SmsCheck smscheck = smsCheckExcutor.getVerifyCode(phoneNum, result);

if (TransferStatus.TRANS_STATUS_FAILURE.equals(result.getResultCode())

|| TransferStatus.BUSS_STATUS_FAILURE.equals(result

.getBussCode())) {

Toast.makeText(SmsCheckActivity.this, result.getBussMsg(),

Toast.LENGTH_LONG).show();

} else {

id = smscheck.getId();

new smsLoadThread().start();

Toast.makeText(SmsCheckActivity.this, R.string.findVerifyCodeSucc,

Toast.LENGTH_LONG).show();

}

}

public void submitVerifycode(View view) {

EditText phoneNumText = (EditText) findViewById(R.id.phoneNum);

EditText verifyCodeText = (EditText) findViewById(R.id.verifyCode);

phoneNum = phoneNumText.getText() == null ? "" : phoneNumText.getText()

.toString();

if (phoneNum == null || phoneNum.equals("")) {

Toast.makeText(SmsCheckActivity.this, R.string.phoneNum,

Toast.LENGTH_LONG).show();

return;

}

verifyCode = verifyCodeText.getText() == null ? "" : verifyCodeText

.getText().toString();

if (verifyCode == null || verifyCode.equals("")) {

Toast.makeText(SmsCheckActivity.this, R.string.verifycode,

Toast.LENGTH_LONG).show();

return;

}

TransferResult result = new TransferResult();

smsCheckExcutor.submitVerifycode(id, phoneNum, verifyCode, result);

if (TransferStatus.TRANS_STATUS_FAILURE.equals(result.getResultCode())

|| TransferStatus.BUSS_STATUS_FAILURE.equals(result

.getBussCode())) {

Toast.makeText(SmsCheckActivity.this, result.getBussMsg(),

Toast.LENGTH_LONG).show();

} else {

Toast.makeText(SmsCheckActivity.this,

R.string.submitVerifyCodeSucc, Toast.LENGTH_LONG).show();

}

}

private void initBean() {

smsCheckExcutor = new SmsCheckExcutor();

}

}

Service代码:

package cn.com.sgcc.eshop.service.smscheck;

import android.app.Service;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Binder;

import android.os.Bundle;

import android.os.IBinder;

import android.telephony.SmsMessage;

public class SmsService extends Service implements Runnable {

private String senderNum = "";

private String verifyCode = "";

// 实例化自定义的Binder类

private final IBinder mBinder = new LocalBinder();

private SMSReceiver receiver;

@Override

public void run() {

// TODO Auto-generated method stub

}

@Override

public void onCreate() {

receiver = new SMSReceiver();

IntentFilter filter = new IntentFilter(

"android.provider.Telephony.SMS_RECEIVED");

this.registerReceiver(receiver, filter);

new Thread(this).start();

super.onCreate();

}

private class SMSReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(

"android.provider.Telephony.SMS_RECEIVED")) {

// 建构一字符串

StringBuilder stringBuilder = new StringBuilder("");

// 接收由Intent传来的数据

Bundle bundle = intent.getExtras();

// 判断Intent是有数据

if (bundle != null) {

// pdus为 android内置短信参数

// identifier,通过bundle.get("")返回一包含pdus的对象

Object[] smsObject = (Object[]) bundle.get("pdus");

// 构造短信对象

SmsMessage[] messages = new SmsMessage[smsObject.length];

for (int i = 0; i < smsObject.length; i++) {

messages[i] = SmsMessage

.createFromPdu((byte[]) smsObject[i]);

}

for (SmsMessage currentMessage : messages) {

// 发送人的电话号码

senderNum = currentMessage

.getDisplayOriginatingAddress();

// 信息内容

stringBuilder.append(currentMessage

.getDisplayMessageBody());

}

}

if (senderNum == null || senderNum.equals(""))

return;

String message = stringBuilder.toString();

if (message == null || message.equals("")

|| !message.contains("sgcc.eshop"))

return;

verifyCode = message.substring(message.indexOf(":") + 1,

message.indexOf(":") + 5);

}

}

}

public class LocalBinder extends Binder {

public SmsService getService() {

// 返回Activity所关联的Service对象,这样在Activity里,就可调用Service里的一些公用方法和公用属性

return SmsService.this;

}

}

@Override

public IBinder onBind(Intent intent) {

return mBinder;

}

public String getVerifyCode() {

return verifyCode;

}

public void setVerifyCode(String verifyCode) {

this.verifyCode = verifyCode;

}

public String getSenderNum() {

return senderNum;

}

public void setSenderNum(String senderNum) {

this.senderNum = senderNum;

}

@Override

public void onDestroy() {

this.unregisterReceiver(receiver);//取消注册的CommandReceiver

super.onDestroy();

}

}

layout.xml代码:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<include

android:id="@+id/login_title_bar"

layout="@layout/title_bar" />

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/phoneNum" />

<EditText

android:id="@+id/phoneNum"

android:layout_width="200dip"

android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/verifycode" />

<EditText

android:id="@+id/verifyCode"

android:layout_width="130dip"

android:layout_height="wrap_content" />

<Button

android:id="@+id/getVerifyCode"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="getVerifyCode"

android:text="@string/getVerifyCode" />

</LinearLayout>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:onClick="submitVerifycode"

android:text="@string/submitVerifycode" />

</LinearLayout>

上面这些代码加上服务端发短信的代码

package cn.com.sgcc.eshop.access.transfer.smscheck;

import org.apache.commons.httpclient.Header;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.NameValuePair;

import org.apache.commons.httpclient.methods.PostMethod;

public class SendSmsHelper {

public static void sendSms(String phoneNum,String verifyCode) throws Exception {

HttpClient client = new HttpClient();

PostMethod post = new PostMethod("http://utf8.sms.webchinese.cn/");

post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码

NameValuePair[] data ={ new NameValuePair("Uid", "wmhyhn"),new NameValuePair("Key", "94c2ea524c097edde9af"),new NameValuePair("smsMob",phoneNum),new NameValuePair("smsText","您在sgcc.eshop中获得的验证码是:"+verifyCode)};

post.setRequestBody(data);

client.executeMethod(post);

Header[] headers = post.getResponseHeaders();

int statusCode = post.getStatusCode();

System.out.println("statusCode:"+statusCode);

for(Header h : headers)

{

System.out.println(h.toString());

}

String result = new String(post.getResponseBodyAsString().getBytes("utf8"));

System.out.println(result);

post.releaseConnection();

}

public static void main(String[] args)throws Exception

{

SendSmsHelper.sendSms("2323","15210716951");

}

}

就是一个验证码的实例

  

爱华网本文地址 » http://www.aihuau.com/a/25101011/96170.html

更多阅读

教你借钱如何打借条,如何写借条欠条 欠条和借条

教你借钱如何打借条,如何写借条欠条——简介在我们的日常生活中,很多事情都与钱相关,在我们日常的人际交往中,亲朋好友之间往往不免会面临借钱与被借的情况。作为债主,在借钱给别人的时候,必须要打借条,因为借条是表明债权债务关系的书面凭

查询、下载QQ空间背景音乐,包括上传歌曲 qq空间背景音乐上传

查询、下载QQ空间背景音乐,包括上传歌曲——简介我们看到别人空间喜欢的背景音乐,很想下载和收藏,但是苦于找不到下载地址而无奈放弃,这个网站很方便的帮助了我们找到下载地址,不仅如此,还可以试听和下载。查询、下载QQ空间背景音乐,包括

二进制数与十六进制数之间如何互相转换 二进制转换十六进制

二进制数与十六进制数之间如何互相转换——简介二进制与十六进制之间的转换与二进制和八进制之间的转换很类似,今天我们来详细看一下:首先,我们来看一下数学关系即24=16,即用四位二进制表示一位八进制。二进制数与十六进制数之间如何互

阴虚体质的形成、表现以及如何食疗 阴虚体质的表现及调养

阴虚质是指人体精、血等阴液亏损,失去润泽脏腑、滋养经脉肌肤的功用,出现虚火上炎的偏颇。只是看上去很健康。阴虚体质的形成、表现以及如何食疗——阴虚体质是如何形成的阴虚体质的形成、表现以及如何食疗 1、先天禀赋,父母遗传;阴虚

二进制如何转十进制,十进制如何转二进制 c 十进制转二进制

二进制如何转十进制,十进制如何转二进制——简介学计算机的朋友刚开始学习时都要接触进制之间的转换,二进制、十进制、八进制、十六进制等,这个是很枯燥的,转来转去就转蒙圈了,别蒙别蒙,今天咱们一个一个搞定,看看二进制和十进制之间如何相

声明:《activity、service、BroadcastReceive之间如何互相通讯,并取回相 android broadcast》为网友演员从事欺骗分享!如侵犯到您的合法权益请联系我们删除