使用SQLite发送SMS

时间:2014-01-26 04:31:48

标签: java android sqlite gps sms

请帮助我..我在发送多条短信时遇到问题,这些短信将发送到我的申请表中注册的联系电话。联系号码存储在SQLite中。该SMS的正文包含用户的当前纬度和经度。 我有网络时发送没有问题,但是当我没有互联网时,短信不会发送。

    gps = new GPSTracker(NotAutoSOSAlert.this);
    if(gps.canGetLocation()) {
            longi=gps.getLongitude();
            lati=gps.getLatitude();
        }
        else {
            gps.showSettingsAlert();
        }
        getLocation();

if(longi != 0 && lati != 0) {
                    SharedPreferences shared = getSharedPreferences("Profile", MODE_PRIVATE);
                    String name = (shared.getString("profileName", "Not Found"));

                    List<ContactsConstructor> contacts = db.getAllContacts();   

                    for (ContactsConstructor cn : contacts) {
                        getLocation();
                        if(name == "") {
                            getProfNameDialog();
                        }

                        Log.d("id", String.valueOf(cn.getID()));
                        Log.d("name", name);
                        Log.d("conName", String.valueOf(cn.getName()));
                        Log.d("num", String.valueOf(cn.getPhoneNumber()));

                            Log.d("both", "not null");
                            String sms2 = cn.getID() + " " + name + " " + cn.getName() + " Help me!!.. My life is in danger!!.. "
                                    + "Here is my location latitude " + lati + " longitude " + longi 
                                    + " https://maps.google.com/?q=" + lati + "," + longi;
                            String sms1 = "1 " + name + " venom Help me!!.. My life is in danger!!.. "
                                    + "Here is my location latitude " + lati + " longitude " + longi 
                                    + " https://maps.google.com/?q=" + lati + "," + longi;
                            String cp = cn.getPhoneNumber();

                            PendingIntent piSent=PendingIntent.getBroadcast(NotAutoSOSAlert.this, 0, new Intent("SMS_SENT"), 0);
                            PendingIntent piDelivered=PendingIntent.getBroadcast(NotAutoSOSAlert.this, 0, new Intent("SMS_DELIVERED"), 0);
                            SmsManager sms = SmsManager.getDefault();
                            sms.sendTextMessage(cp, null, sms2, piSent, piDelivered); } }

getLocation函数

    private void getLocation() {
    // TODO Auto-generated method stub
    listUpdaterExecuter = new ScheduledThreadPoolExecutor(5);
    listUpdaterExecuter.scheduleAtFixedRate(new Runnable() {
        private Runnable update = new Runnable() {
            @Override
            public void run() {          
              // ln.setText(""+lng);
              // lt.setText(""+lat);
                gps = new GPSTracker(NotAutoSOSAlert.this);
                if(gps.canGetLocation()) {
                longi=gps.getLongitude();
                lati=gps.getLatitude();
                }
            }
        };

 @Override
        public void run() {
            runOnUiThread(update);
        }
    }, 5, 20, TimeUnit.SECONDS);
}

onResume

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

    smsSentReceiver=new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS has been sent", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(getBaseContext(), "Generic Failure", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(getBaseContext(), "No Service", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "Radio Off", Toast.LENGTH_SHORT).show();
                break;
            default:
                Toast.makeText(getBaseContext(), "Generic Failure", Toast.LENGTH_SHORT).show();
                break;
            }

        }
    };
    smsDeliveredReceiver=new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            switch(getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS Delivered", Toast.LENGTH_SHORT).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
    registerReceiver(smsDeliveredReceiver, new IntentFilter("SMS_DELIVERED"));
}

onPause

    @Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
     unregisterReceiver(smsSentReceiver);
     unregisterReceiver(smsDeliveredReceiver);
}

GPSTracker课程

    public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }

            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        }

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

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }      
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    if(locationManager != null){
        locationManager.removeUpdates(this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS  or Wireless Networks is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

ContactsConstructor类

    public class ContactsConstructor {
//private variables
    int _id;
    String _name;
    String _phone_number;

    // Empty constructor
    public ContactsConstructor(){

    }
    // constructor
    public ContactsConstructor(int id, String name, String _phone_number){
        this._id = id;
        this._name = name;
        this._phone_number = _phone_number;
    }

    // constructor
    public ContactsConstructor(String name, String _phone_number){
        this._name = name;
        this._phone_number = _phone_number;
    }
    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    // getting name
    public String getName(){
        return this._name;
    }

    // setting name
    public void setName(String name){
        this._name = name;
    }

    // getting phone number
    public String getPhoneNumber(){
        return this._phone_number;
    }

    // setting phone number
    public void setPhoneNumber(String phone_number){
        this._phone_number = phone_number;
    }

}

和ContactsDbHelper Class

    public class ContactsDbHelper extends SQLiteOpenHelper {

static String DATABASE_NAME="alerto";
public static final String TABLE_NAME="contacts";
public static final String KEY_FNAME="fname";
public static final String KEY_NUMBER="number";
public static final String KEY_ID="id";

public ContactsDbHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_NUMBER+" TEXT)";
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}

// Getting All Contacts
    public List<ContactsConstructor> getAllContacts() {
        List<ContactsConstructor> contactList = new ArrayList<ContactsConstructor>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                ContactsConstructor contact = new ContactsConstructor();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

}

当我使用互联网时的Logcat(没问题)

  

01-26 12:30:10.969:D / id(17370):1

     

01-26 12:30:10.969:D / name(17370):Jingo

     

01-26 12:30:10.969:D / conName(17370):毒液

     

01-26 12:30:10.969:D / num(17370):09208689479

     

01-26 12:30:10.989:D / id(17370):2

     

01-26 12:30:10.989:D / name(17370):Jingo

     

01-26 12:30:10.989:D / num(17370):67993

     

01-26 12:30:11.009:D / id(17370):3

     

01-26 12:30:11.009:D / name(17370):Jingo

     

01-26 12:30:11.009:D / conName(17370):jbmdd

     

01-26 12:30:11.009:D / num(17370):4489

不使用互联网时的Logcat。

  

01-26 12:35:08.999:D / id(17665):1

     

01-26 12:35:08.999:D / name(17665):Jingo

     

01-26 12:35:08.999:D / conName(17665):毒液

     

01-26 12:35:08.999:D / num(17665):09208689479

它仅记录我的应用程序中注册的第一个联系人。请帮帮我伙计..提前谢谢你!

我已经解决了这些问题。用户只需要检查位置和位置下的使用无线网络。无论用户是否连接到WiFi,Android手机的安全菜单

现在的问题是,如何检查用户是否检查位置和位置下的无线网络。 Android手机的安全菜单?请帮我解决这些问题

0 个答案:

没有答案