onReceive BroadcastReceiver在调试中崩溃

时间:2012-03-09 04:11:35

标签: android debugging broadcastreceiver

我正在创建一个短信转发应用,而且我的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) {


        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String device = "15555215556";
            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");
                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());
        }
    }
}

我的活动课

package sms.pack;

import java.util.List;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class SMS_forwardActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void openInbox() {
        String application_name = "com.android.mms";
        try {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");

        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        List<ResolveInfo> resolveinfo_list = this.getPackageManager()
        .queryIntentActivities(intent, 0);

        for (ResolveInfo info : resolveinfo_list) {
        if (info.activityInfo.packageName
        .equalsIgnoreCase(application_name)) {
        launchComponent(info.activityInfo.packageName,
        info.activityInfo.name);
        break;
        }
        }
        } catch (ActivityNotFoundException e) {
        Toast.makeText(
        this.getApplicationContext(),
        "There was a problem loading the application: "
        + application_name, Toast.LENGTH_SHORT).show();
        }
    }

    private void launchComponent(String packageName, String name) {
    Intent launch_intent = new Intent("android.intent.action.MAIN");
    launch_intent.addCategory("android.intent.category.LAUNCHER");
    launch_intent.setComponent(new ComponentName(packageName, name));
    launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(launch_intent);
    }

    public void startListening(View view)
    {
        Intent i = new Intent();
        i.setClassName("sms.pack","sms.pack.SmsListener");
        sendBroadcast(i);
    }

}

main.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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Listen" 
        android:onClick="startListening"/>

</LinearLayout>

的manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sms.pack"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />


    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SMS_forwardActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".listener.SmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
    </receiver>
    </application>

</manifest>

在活动类中有一个调用statListening类的按钮,后者又启动SmsListener类,该类侦听来自某个数字的短信,然后将消息内容保存到SD卡。 / p>

当我运行项目并单击Listen时,然后从另一个VM手机发送短信,我发现SD卡中没有保存的文件。所以我决定运行调试

在调试模式下,我单击Listen按钮,然后我发送消息,我在调试中收到错误

ActivityThread.handleReceiver(ActivityThread $ handleReceiver)line1773

我无法弄清楚代码有什么问题

2 个答案:

答案 0 :(得分:1)

在android清单文件中指定权限,如下所示

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>

并指定监听器的优先级,以便将短信收到您的应用

<receiver android:name=".SmsReceiver" >
        <intent-filter android:priority="50" >
            <action
                android:name="android.provider.Telephony.SMS_RECEIVED"
                android:enabled="true" />
        </intent-filter>
    </receiver>

答案 1 :(得分:0)

我建议你将接收器块放在应用程序块之外的清单中。

除掉与启动BroadcastReceiver相关的所有代码 - 你不需要启动任何东西,Android会为你做这件事,因为你注册了意图。

PVS