0

当您收到短信“更新”时,我试图显示一条消息。但是我的应用程序强制关闭。给出代码和日志猫。我正在eclipse中的模拟器上对其进行测试。正在接收短信,但在收到“UPDATE”时不显示“HI”消息。请帮忙!!

SrvSmsListener.java

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsMessage;
import android.widget.Toast;


public class SrvSmsListener extends Service 
{


private BroadcastReceiver IncomingSMSReceiver = new BroadcastReceiver() {
    private static final String SMS_RECEIVED =
            "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context _context, Intent _intent) {
        if (_intent.getAction().equals(SMS_RECEIVED)) {
            Bundle bundle = _intent.getExtras();
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");

                SmsMessage[] messages = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++)
                    messages[i] = SmsMessage
                            .createFromPdu((byte[]) pdus[i]);
                for (SmsMessage message : messages) {
                    String strPhoneNo = message.getOriginatingAddress();
                    String msg = message.getMessageBody();

                    if (msg.startsWith("UPDATE"))
                    {
                        Toast.makeText(getApplicationContext(), "Got it", Toast.LENGTH_LONG).show();
                        // this stops notifications to others


                        this.abortBroadcast();
                        // do what you want

                    }
                }
            }
        }
    }
};

public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

public void onCreate() {
    final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    IntentFilter filter = new IntentFilter(SMS_RECEIVED);
    BroadcastReceiver receiver = IncomingSMSReceiver;
    registerReceiver(receiver, filter);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    if (IncomingSMSReceiver != null)
    {
        unregisterReceiver(IncomingSMSReceiver);
    }
}

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

}
}

主.java

public class Main extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
long start;
long stop;
int x, y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat ;
int longi; 





@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);



    Button button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(Main.this, SrvSmsListener.class);
            startActivity(intent);
        }
    });

    map = (MapView)findViewById(R.id.mv);
    map.setBuiltInZoomControls(true);

    Touchy t = new Touchy();
    overlayList = map.getOverlays();
    overlayList.add(t);

    d = getResources().getDrawable(R.drawable.pinn);

    //Placing pintpoint
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();

    towers = lm.getBestProvider(crit, false);
    Location location = lm.getLastKnownLocation(towers);

    if (location != null){
        lat = (int) (location.getLatitude() *1E6);
        longi= (int) (location.getLongitude() *1E6);



        GeoPoint ourLocation = new GeoPoint(lat,longi);
        OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
        CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
        custom.insertPinpoint(overlayItem);
        overlayList.add(custom);
    }else{
        Toast.makeText(Main.this, "Couldnt get provider", Toast.LENGTH_SHORT).show();
    }





}

@Override
protected void onPause() {
    // TODO Auto-generated method stub

    super.onPause();
    lm.removeUpdates(this);
}


@Override
protected void onResume() {
    // TODO Auto-generated method stub

    super.onResume();
    lm.requestLocationUpdates(towers, 500, 1, this );
}


    @Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}



class Touchy extends Overlay{
    public boolean onTouchEvent(MotionEvent e, MapView m){
    if (e.getAction() == MotionEvent.ACTION_DOWN){
        start = e.getEventTime();

    }
    if (e.getAction() == MotionEvent.ACTION_UP){
        stop = e.getEventTime();
        x = (int) e.getX();
        y = (int) e.getY();
        touchedPoint = map.getProjection().fromPixels(x, y);

    }
    if (stop - start > 1500){
        AlertDialog alert = new AlertDialog.Builder(Main.this).create();
        alert.setTitle("Pick Option");


        alert.setButton("Hello", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
                CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
                custom.insertPinpoint(overlayItem);
                overlayList.add(custom);



        }
        });
        alert.setButton3("Get Address", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
            Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
            try{
                List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6 , 1);
                if (address.size() > 0){
                    String display = "";
                    for (int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){

                        display += address.get(0).getAddressLine(i) + "\n";
                    }
                    Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
                    t.show();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
            }
        }});
        alert.setButton2("Toggle View", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                if (map.isSatellite()){
                    map.setSatellite(false);
                    map.setStreetView(true);
                }else{
                    map.setStreetView(false);
                    map.setSatellite(true);
                }
            }
});
        alert.setButton("Place a Pin", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
                CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
                custom.insertPinpoint(overlayItem);
                overlayList.add(custom);

            }


        });
        alert.show();
        return true;
    }

        return false;
    }

}



public void onLocationChanged(Location l) {
    // TODO Auto-generated method stub
    lat = (int) (l.getLatitude() *1E6);
    longi = (int) (l.getLongitude() *1E6);
    GeoPoint ourLocation = new GeoPoint(lat,longi);
    OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
    CustomPinPoint custom = new CustomPinPoint(d, Main.this);   
    custom.insertPinpoint(overlayItem);
    overlayList.add(custom);

}




public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}




public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}




public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

CustomPinPoint.java

public class CustomPinPoint extends ItemizedOverlay<OverlayItem> {

private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;

public CustomPinPoint(Drawable defaultMarker) {
    super(boundCenter(defaultMarker));
    // TODO Auto-generated constructor stub
}

public CustomPinPoint(Drawable m, Context context ) {
    // TODO Auto-generated constructor stub
    this(m);
    c = context;
}

@Override
protected OverlayItem createItem(int i) {
    // TODO Auto-generated method stub
    return pinpoints.get(i);
}

@Override
public int size() {
    // TODO Auto-generated method stub
    return pinpoints.size();
}


public void insertPinpoint(OverlayItem item){
    pinpoints.add(item);
    this.populate();
}
}

显现

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

<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">   

    <uses-library android:name="com.google.android.maps" />
    <activity
        android:name=".Main"
        android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:enabled="true"
        android:name=".SrvSmsListener" />
    <receiver android:name=".IncomingSMSReceiver"> 
    <intent-filter> 
        <action android:name=
            "android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter> 
</receiver>
</application>

</manifest>

原木猫

04-08 16:44:57.054: W/dalvikvm(311): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-08 16:44:57.244: E/AndroidRuntime(311): FATAL EXCEPTION: main
04-08 16:44:57.244: E/AndroidRuntime(311): java.lang.RuntimeException: Unable to   instantiate receiver com.mehul.googlemaps.IncomingSMSReceiver:   java.lang.ClassNotFoundException: com.mehul.googlemaps.IncomingSMSReceiver in loader   dalvik.system.PathClassLoader[/system/framework/com.google.android.maps.jar:/data/app/com.mehul.googlemaps-2.apk]
04-08 16:44:57.244: E/AndroidRuntime(311):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2789)
04-08 16:44:57.244: E/AndroidRuntime(311):  at android.app.ActivityThread.access$3200(ActivityThread.java:125)
04-08 16:44:57.244: E/AndroidRuntime(311):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083)
04-08 16:44:57.244: E/AndroidRuntime(311):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-08 16:44:57.244: E/AndroidRuntime(311):  at android.os.Looper.loop(Looper.java:123)
04-08 16:44:57.244: E/AndroidRuntime(311):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-08 16:44:57.244: E/AndroidRuntime(311):  at java.lang.reflect.Method.invokeNative(Native Method)
04-08 16:44:57.244: E/AndroidRuntime(311):  at java.lang.reflect.Method.invoke(Method.java:521)
04-08 16:44:57.244: E/AndroidRuntime(311):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-08 16:44:57.244: E/AndroidRuntime(311):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-08 16:44:57.244: E/AndroidRuntime(311):  at dalvik.system.NativeStart.main(Native Method)
04-08 16:44:57.244: E/AndroidRuntime(311): Caused by: java.lang.ClassNotFoundException: com.mehul.googlemaps.IncomingSMSReceiver in loader dalvik.system.PathClassLoader[/system/framework/com.google.android.maps.jar:/data/app/com.mehul.googlemaps-2.apk]
04-08 16:44:57.244: E/AndroidRuntime(311):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
04-08 16:44:57.244: E/AndroidRuntime(311):  at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
04-08 16:44:57.244: E/AndroidRuntime(311):  at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
04-08 16:44:57.244: E/AndroidRuntime(311):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2780)
04-08 16:44:57.244: E/AndroidRuntime(311):  ... 10 more
4

4 回答 4

0

您在 AndroidManifest 中指定的 Receiver 类必须扩展 BroadcastReceiver。在您的情况下,您指定:

<receiver android:name=".SrvSmsListener"> 

但是这个类扩展了服务:

public class SrvSmsListener extends Service 
于 2012-04-08T07:32:45.827 回答
0

那个代码是我的;)

您必须在清单中添加您的服务:

 <service
            android:enabled="true"
            android:name=".SrvSmsListener" />
于 2012-04-08T08:04:03.720 回答
0

试试这个

public class Sms2Activity extends BroadcastReceiver 
{

String message,number;

@Override
public void onReceive(Context context, Intent intent)
{
    Toast.makeText(context, "incomming message", Toast.LENGTH_SHORT).show();

    //Get values from Bundle - get incoming number


    Bundle bundle = intent.getExtras();
    SmsMessage[ ] msgs = null;
    String str = "";
    if (bundle != null)
    {





        //---retrieve the received message here ---
        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]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
            message = msgs[i].getMessageBody().toString();
            number = msgs[i].getOriginatingAddress();
        }
       // ........first show sms here.....
       Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); 



   }
于 2012-04-08T08:12:47.397 回答
0

您正在将服务注册为应用程序的接收器。注册广播接收器 IncomingSMSReceiver 以收听短信。改变这个:

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

<receiver android:name=".SrvSmsListener.IncomingSMSReceiver"> 
        <intent-filter> 
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" /> 
        </intent-filter> 
    </receiver>
于 2012-04-08T08:18:05.307 回答