接收Android短信

时间:2012-12-09 15:52:35

标签: java android sms

我一直在尝试这么多不同的东西来让这个演示运行但我无法让它运行正常..

这是我的Manifest.xml

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

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="9" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="com.example.messagekeeper.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


    <receiver android:name=".SmsReciever"> 
        <intent-filter> 
            <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
        </intent-filter> 
    </receiver> 

</application>

</manifest>

这是我的MainActivity类(没有任何内容):

package com.example.messagekeeper;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

这是SmsReciever类:

package com.example.messagekeeper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

class SmsReciever extends BroadcastReceiver{
@Override
  public void onReceive(Context context, Intent intent){
    Object[] pdus=(Object[])intent.getExtras().get("pdus");
    SmsMessage shortMessage=SmsMessage.createFromPdu((byte[]) pdus[0]);

        Log.d("SMSReceiver","SMS message sender: "+
               shortMessage.getOriginatingAddress());
        Log.d("SMSReceiver","SMS message text: "+
               shortMessage.getDisplayMessageBody());


  }

}

当我收到消息时,我希望它能在我的应用上看到它。在这种情况下,我的意思是当我使用此代码并在模拟器上运行我的应用程序,并从一个模拟器发送消息到另一个,我的应用程序崩溃,我收到此错误:http://puu.sh/1yZub

1 个答案:

答案 0 :(得分:1)

如果您完全按照原样复制了代码,则可能在开头时错过了public关键字。

更改class SmsReciever extends BroadcastReceiver{

public class SmsReciever extends BroadcastReceiver{