一个将在后台运行的服务?

时间:2012-04-06 07:58:56

标签: android service sms location

考虑2个人拥有该应用。当其中一个用户想要知道另一个用户的位置时,他发送短信(内容可以是任何东西或特定的)。当其他用户获得短信时(如果可能的话,他不应该知道他收到了短信)。然后将他的位置发回给要求它的用户。 希望解释清楚。

public void onReceive(Context context, Intent intent) 
{   
//this stops notifications to others
this.abortBroadcast();

//---get the SMS message passed in---
Bundle bundle = intent.getExtras();   
SmsMessage[] msgs = null;
String str = "";            
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]);                
        str += "SMS from " + msgs[i].getOriginatingAddress();
        from = msgs[i].getOriginatingAddress();
        str += " :";
        str += msgs[i].getMessageBody().toString();
        msg = msgs[i].getMessageBody().toString();
        str += "\n"; 
    }
    if(checksomething){
        //make your actions
        //and no alert notification and sms not in inbox
    }
    else{
        //continue the normal process of sms and will get alert and reaches inbox
        this.clearAbortBroadcast();
    }
  }

我收到了这段代码......我应该在这方面做些什么改变??

2 个答案:

答案 0 :(得分:1)

您需要的不是服务,而是用户所在位置的广播接收器。

public class SmsReceiver extends BroadcastReceiver {


    private static final String ACTION_SMS_RECEIVED = 
        "android.provider.Telephony.SMS_RECEIVED";


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


            if(intent.getAction().equals(ACTION_SMS_RECEIVED)){
                //your code to get location here.
            }

    }
}

答案 1 :(得分:0)

通过扩展Service来创建正常服务。例如

    public class LocalService extends Service {
        @Override
        public void onCreate() {
  // SEND USER LOCATION
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
            return START_STICKY;
        }
        @Override
        public void onDestroy() {
        }
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
       }

开始您的服务:

  public final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
           // CHECK SMS IF IT IS FOR SEND LOCTION OR ANY OTHER SMS
            if (action.equals(ACTION_SMS_RECEIVED)) {
               //START SERVICE HERE
            }

        }
    };

并为ACTION_BOOT_COMPLETED ,ACTION_SCREEN_ON,ACTION_SCREEN_OFF注册BroadcastReceiver以处理服务的启动和停止

也许有用: - )