2013-11-26 51 views
1

我正在尋找一個應用程序來檢查設備的速度(如果駕駛等),並且如果它在預設的閾值下,它會通過用標準通知將SMS發送到標準接收設備。如果標準失敗(移動得太快)。我希望它仍然可以通過短信,抑制通知,並自動向發件人發送回覆。如何根據條件將SMS傳遞到默認的SMS應用程序

目前,這是我剛纔接收和發送:

package biz.midl.drivereply; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.telephony.SmsManager; 
import android.telephony.SmsMessage; 

public class MainActivity extends BroadcastReceiver { 

    int MAX_SPEED = 1000; //will have a change method later 

    @Override 
    public void onReceive(Context arg0, Intent arg1) { 
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); //context cannot be resolved 
    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

     if (lastKnownLocation.getSpeed() > MAX_SPEED) 
     { 
      Bundle extras = intent.getExtras(); //intent cannot be resolved 

      if (extras == null) 
      { 
       return; 
      } 

      abortBroadcast(); 

      Object[] pdus = (Object[]) extras.get("pdus"); 
      SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[0]); 

      String origNumber = msg.getOriginatingAddress();    
      String reply = "The user is busy. Try again later."; 

      SmsManager.getDefault().sendTextMessage(origNumber, null, reply, null, null);   
     } 
    } 
} 

我與評論行之後顯示的錯誤。

回答

1

由於您只對收到短信時的速度感興趣,因此無需持續監控您的位置和速度。在這種情況下,您的BroadcastReceiver應該實施以播放SMS_RECEIVED廣播。要做到這一點,註冊您的接收器在您的清單中,像這樣:

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

然後,在onReceive()方法,簡單地檢查其速度最後已知的位置,並回答如果必要的話:

@Override 
public void onReceive(Context context, Intent intent) 
{ 
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    if (lastKnownLocation.getSpeed() > MAX_SPEED) 
    { 
     Bundle extras = intent.getExtras(); 

     if (extras == null) 
     { 
      return; 
     } 

     abortBroadcast(); 

     Object[] pdus = (Object[]) extras.get("pdus"); 
     SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[0]); 

     String origNumber = msg.getOriginatingAddress();    
     String reply = "The user is busy. Try again later."; 

     SmsManager.getDefault().sendTextMessage(origNumber, null, reply, null, null);   
    } 
} 

在上面的例子中,接收者的優先級被設置爲最大值(999),所以它將首先收到SMS_RECEIVED廣播。然後,如果速度大於您定義的速度限制,則中止廣播,並向發件人發送回覆。否則,什麼都不做,並且廣播將繼續到註冊獲取它的其他接收器,如平臺SMS應用程序。

相關問題