我正在创建一个短信付费应用。我目前有两节课;一个主Activity类,用于修改设置和使用BroardcastReceiver的smsListener类。但是,我无法弄清楚如何启动smsListener类。 ref的smsListener类的代码
package sms.pack;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.SmsMessage;
import android.util.Log;
public class SmsListener extends BroadcastReceiver{
private SharedPreferences preferences;
@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(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String device = "mobile_num_here"; //number to listen for
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
if (msg_from == device)
{
savedata(msgBody);
}
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
public void savedata(String data)
{
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File gpxfile = new File(root, "smsfile.txt");//remember change directory
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write(data);
out.close();
}
} catch (IOException e) {
Log.e(data,"Could not write file " + e.getMessage());
}
}
}
我正计划使用意图启动那是不行的,方法如下
public void startListening(View view)
{
Intent i = new Intent();
i.setClassName("sms.pack","sms.pack.SmsListener");
startActivity(i);
}
答案 0 :(得分:1)
您只能使用startActivity启动活动 BroadcastReceiver侦听广播意图。使用sendBroadcast(意图广播)。确保在清单文件中放置receiver标记。
答案 1 :(得分:0)
您必须先注册广播接收器。
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity ....
</activity>
<receiver android:name="SmsListener ">
<intent-filter android:priority="100" >
<action android:name="android.intent.action.DATA_SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
通过以下方式启动广播接收器:
Intent i = new Intent(your_Activity_Class.this, SmsListener.class);
startActivity(i);
希望得到这个帮助。