0

我正在尝试使用 SMS 作为激活器来创建手机定位器,但是当我向手机发送短信时,应用程序总是崩溃(强制关闭):

这是我的课程代码:

public class SMSReceiver extends BroadcastReceiver{
        private static final String FAR_MODE_KEY = "farmode";
        private String FarModeKeyword;

        @Override
        public void onReceive(Context context, Intent intent) {

            prefs = getSharedPreferences(Keywords, MODE_PRIVATE);
            FarModeKeyword = prefs.getString(FAR_MODE_KEY, "");

            //---get the SMS message passed in---
            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String message = "";
            String number = "";
            if (bundle != null)
            {
                //---retrieve the SMS message received---
                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]);
                    message += msgs[i].getMessageBody().toString();
                }

                for (int i=0; i<msgs.length; i++)
                {
                    msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                    number += msgs[i].getOriginatingAddress();
                }

            }

            if (message == FarModeKeyword)
            {
                Toast.makeText(getBaseContext(),
                        message,
                        Toast.LENGTH_SHORT).show();
                String loc = "";
                loc = getLocation();
                Toast.makeText(getBaseContext(),
                        loc,
                        Toast.LENGTH_SHORT).show();
                sendSMS(number, loc);
            }

        }

        private void sendSMS(String phoneNumber, String message)
        {
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, null, null);
        }

        private String getLocation ()
        {
            // Get the location manager
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            Criteria criteria = new Criteria ();
            String bestProvider = locationManager.getBestProvider(criteria, false);
            Location location = locationManager.getLastKnownLocation(bestProvider);

            LocationListener MyLocListener = new loc_listener();
            locationManager.requestLocationUpdates(bestProvider, 1000, 1, MyLocListener); 

            String add = "";

            Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
            try 
            {
                List<Address> addresses = geoCoder.getFromLocation(lat,lon, 1);

                if (addresses.size() > 0)
                {
                    for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
                    add += addresses.get(0).getAddressLine(i) + "\n";
                }

            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }

            locationManager.removeUpdates(MyLocListener);
            return add;

        }

        public class loc_listener implements LocationListener
        {     
              public void onLocationChanged(Location l) {
                  lat = l.getLatitude();
                  lon = l.getLongitude();         
              }
              public void onProviderEnabled(String p) {
              }

              public void onProviderDisabled(String p) {
              }

              public void onStatusChanged(String p, int status, Bundle extras){
              }      
        }
    }

这是清单文件:

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

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

    <uses-feature
      android:glEsVersion="0x00020000"
      android:required="true"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="locateodroid.james.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyBBo4h4fDksXasHd7iCgIg0A5wTriToW8w"/>

     <permission
          android:name="locateodroid.james.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>


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

        <activity
            android:name="locateodroid.james.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=".receiver.StartMyServiceAtBootReceiver"
            android:enabled="true"
            android:exported="true"
            class="locateodroid.james.receiver.StartMyServiceAtBootReceiver"
            android:label="StartMyServiceAtBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <receiver android:name="locateodroid.james.sms.SMSReceiver"
            class="locateodroid.james.sms.SmsReceiver"
            android:label="SMSReceiver">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

这是错误的logcat:

    02-05 04:03:25.169: E/AndroidRuntime(430): FATAL EXCEPTION: main
02-05 04:03:25.169: E/AndroidRuntime(430): java.lang.RuntimeException: Unable to instantiate receiver locateodroid.james.sms.SMSReceiver: java.lang.ClassNotFoundException: locateodroid.james.sms.SMSReceiver in loader dalvik.system.PathClassLoader[/data/app/locateodroid.james-1.apk]
02-05 04:03:25.169: E/AndroidRuntime(430):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:1773)
02-05 04:03:25.169: E/AndroidRuntime(430):  at android.app.ActivityThread.access$2400(ActivityThread.java:117)
02-05 04:03:25.169: E/AndroidRuntime(430):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
02-05 04:03:25.169: E/AndroidRuntime(430):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-05 04:03:25.169: E/AndroidRuntime(430):  at android.os.Looper.loop(Looper.java:123)
02-05 04:03:25.169: E/AndroidRuntime(430):  at android.app.ActivityThread.main(ActivityThread.java:3683)
02-05 04:03:25.169: E/AndroidRuntime(430):  at java.lang.reflect.Method.invokeNative(Native Method)
02-05 04:03:25.169: E/AndroidRuntime(430):  at java.lang.reflect.Method.invoke(Method.java:507)
02-05 04:03:25.169: E/AndroidRuntime(430):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-05 04:03:25.169: E/AndroidRuntime(430):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-05 04:03:25.169: E/AndroidRuntime(430):  at dalvik.system.NativeStart.main(Native Method)
02-05 04:03:25.169: E/AndroidRuntime(430): Caused by: java.lang.ClassNotFoundException: locateodroid.james.sms.SMSReceiver in loader dalvik.system.PathClassLoader[/data/app/locateodroid.james-1.apk]
02-05 04:03:25.169: E/AndroidRuntime(430):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
02-05 04:03:25.169: E/AndroidRuntime(430):  at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
02-05 04:03:25.169: E/AndroidRuntime(430):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
02-05 04:03:25.169: E/AndroidRuntime(430):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:1764)
02-05 04:03:25.169: E/AndroidRuntime(430):  ... 10 more

我在这个错误上工作了将近 2 天,但我仍然没有答案,有人可以帮我解决这个问题吗?提前致谢!

更新

第一个问题现在已经解决了,但是另一个错误是,当我收到一条短信时抛出了 NullPointerException

package locateodroid.james;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.EditText;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver{

    public SharedPreferences prefs;
    private String FarModeKeyword;
    private String Keywords = "prefmode";
    private Double lat;
    private Double lon;
    private static final String FAR_MODE_KEY = "farmode";
    private Context con;

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context,
                "test",
                Toast.LENGTH_SHORT).show();
        con = context;
        prefs = getSharedPreferences(Keywords, Context.MODE_PRIVATE);
        FarModeKeyword = prefs.getString(FAR_MODE_KEY, "");

        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String message = "";
        String number = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            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]);
                message += msgs[i].getMessageBody().toString();
            }

            for (int i=0; i<msgs.length; i++)
            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                number += msgs[i].getOriginatingAddress();
            }

        }

        if (message == FarModeKeyword)
        {
            Toast.makeText(context,
                    message,
                    Toast.LENGTH_SHORT).show();
            String loc = "";
            loc = getLocation();
            Toast.makeText(context,
                    loc,
                    Toast.LENGTH_SHORT).show();
            sendSMS(number, loc);
        }

    }

    private SharedPreferences getSharedPreferences(String keywords2,
            int modePrivate) {
        // TODO Auto-generated method stub
        return null;
    }

    private void sendSMS(String phoneNumber, String message)
    {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }

    private String getLocation ()
    {
        // Get the location manager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria ();
        String bestProvider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(bestProvider);

        LocationListener MyLocListener = new loc_listener();
        locationManager.requestLocationUpdates(bestProvider, 1000, 1, MyLocListener); 

        String add = "";

        Geocoder geoCoder = new Geocoder(con, Locale.getDefault());
        try 
        {
            List<Address> addresses = geoCoder.getFromLocation(lat,lon, 1);

            if (addresses.size() > 0)
            {
                for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
                add += addresses.get(0).getAddressLine(i) + "\n";
            }

        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }

        locationManager.removeUpdates(MyLocListener);
        return add;

    }

    private LocationManager getSystemService(String locationService) {
        // TODO Auto-generated method stub
        return null;
    }

    public class loc_listener implements LocationListener
    {     
          public void onLocationChanged(Location l) {
              lat = l.getLatitude();
              lon = l.getLongitude();         
          }
          public void onProviderEnabled(String p) {
          }

          public void onProviderDisabled(String p) {
          }

          public void onStatusChanged(String p, int status, Bundle extras) {
          }      
    }
}

该类现在返回 NullPointerException 错误:(

4

1 回答 1

0

它无法找到类:

Caused by: java.lang.ClassNotFoundException: locateodroid.james.sms.SMSReceiver

你确定包参考吗?

这很可能来自您的接收者的班级行:

class="locateodroid.james.sms.SmsReceiver"

更新

您不能使用这些上下文属性的原因是因为它们是STATIC常量

这意味着您从基类中获取它们(不需要实例),如下所示:

Context.MODE_PRIVATE 
于 2013-02-04T20:12:22.883 回答