您的位置:首页 > 其它

提示接收到信息的程序

2012-08-20 15:42 162 查看
上篇文章写了发送信息,所以接下来写一篇小小文章关于接收到信息,并且弹出一个小小的toast(toast是可以自定义的,如果你觉得系统的不好看,你可以自己定义一个,但是我为了方便就使用系统提供的了)

1、首界面的xml:

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

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView

android:textSize="20dip"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/myString"

android:gravity="center_horizontal"

/>

<Button

android:id="@+id/ok"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="20dip"

android:text="@string/ok"

android:layout_gravity="center_horizontal"

/>

</LinearLayout>

图示:



2、该界面的java代码:

package com.receive;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class ReceiveMSNActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button ok = (Button) findViewById(R.id.ok);

ok.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

System.exit(0); //退出该程序

}

});

}

}

4、开发一个广播类,用来监听收到信息的广播:

package com.receive;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsMessage;

import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){

Bundle bundle = intent.getExtras();

if(bundle != null){ //当数据不为空时

Object[] myObject = (Object[]) bundle.get("pdus"); // 分析数据

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

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

messages[i] = SmsMessage.createFromPdu((byte[]) myObject[i]);

}

StringBuilder sb = new StringBuilder();

for(SmsMessage tempSmsMessage : messages){ //循环信息数组

sb.append("收到来自:\n");

sb.append(tempSmsMessage.getDisplayOriginatingAddress() + "\n");

sb.append("内容为:\n");

sb.append(tempSmsMessage.getDisplayMessageBody());

}

Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();

}

}

}

}

5、效果如下图所示:

a、在5556模拟器上发送信息



b、在5554模拟器上接收信息:



6、该简单程序就到这先,如以后又改进再补充上去。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐