Vicky Vicky - 1 month ago 16
Android Question

Broadcast Reciever Not Working, Testing on Moto G, Using SMS

I am having an issue with BroadcastRecievers. I am registering them, but they are not receiving the broadcast. My goal is to create an SMS Autoresponder that will send location data.
Here is my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.voodoo.autoresponder">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".SmsAutorespond"
android:label="SMS Autorespond" >
</service>
</application>

</manifest>


Here is my MainActivity:

package com.voodoo.autorespond;

import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
ToggleButton toggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = (ToggleButton) findViewById(R.id.streamButton);
final AutoBroadcastReceiver r = new AutoBroadcastReceiver();
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
MainActivity.this.registerReceiver(r, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
Log.i("MainActivity", "registered reciever");
}
});
}

}


Here is my BroadcastReciever:

package com.voodoo.autorespond;


import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.telephony.SmsMessage;
import android.telephony.SmsManager;
import android.util.Log;

public class AutoBroadcastReceiver extends BroadcastReceiver {

private static final String TAG = "AutoBroadcastReceiver";

private static String mLastAddress = "";
private static String mLastMsg = "";
private double mLocationLat;
private double mLocationLon;

@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Broadcast recieved");
try{
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {

Bundle extras = intent.getExtras();
if (extras != null) {
Object[] smsextras = (Object[]) extras.get("pdus");
for (int i = 0; i < smsextras.length; i++) {
SmsMessage smsmsg = SmsMessage
.createFromPdu((byte[]) smsextras[i]);
String strMsgBody = smsmsg.getMessageBody().toString();
String strMsgSrc = smsmsg.getOriginatingAddress();

if (!mLastAddress.contentEquals(strMsgSrc)
&& !mLastMsg.contentEquals(strMsgBody)) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {

@Override
public void onLocationChanged(Location location) {
mLocationLat = location.getLatitude();
mLocationLon = location.getLatitude();
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, locationListener);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(strMsgSrc, null, context.getString(R.string.autoResponse) + "maps.google.com/q=" + mLocationLat + ","
+ mLocationLon, null, null);
mLastAddress = strMsgSrc;
mLastMsg = strMsgBody;

Log.i(TAG, "Sending response for SMS");
}
else{
Log.i(TAG, "Not sending duplicate response for SMS");
}

this.abortBroadcast();

Log.i(TAG, "Got sms: " + i + " " + strMsgSrc + " " + strMsgBody);
}
}
} else if (intent.getAction() != null) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)
|| intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
context.startService(new Intent(context, SmsAutorespond.class));
}
}
} catch(SecurityException se) {
return;
}
}

}


Here is my service:

package com.voodoo.autorespond;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class SmsAutorespond extends Service {

private static final String TAG = "SmsAutorespond";

@Override
public ComponentName startService(Intent service) {
return super.startService(service);
}

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

@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "registering receiver");
AutoBroadcastReceiver r = new AutoBroadcastReceiver();

try{
unregisterReceiver(r);
registerReceiver(r, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
} catch(IllegalArgumentException e){}
}
}


Thank you!(I am testing this on a 2nd Gen Moto G)

Answer

Register Receiver in manifest. Example.

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

Also, check phone API level if it's 6.0 or more then you need to Requesting Permissions at Run Time Doc

Add this code onCreate

    ActivityCompat.requestPermissions(PostListFragment.this,
            new String[]{Manifest.permission.RECEIVE_SMS,Manifest.permission.SEND_SMS,Manifest.permission.READ_SMS},
            1);

Override this method in Activity

@Override
 public void onRequestPermissionsResult(int requestCode,
                                   String permissions[], int[] grantResults) {
    switch (requestCode) {
    case 1: {

      // If request is cancelled, the result arrays are empty.
      if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // permission was granted, yay! Do the
            // contacts-related task you need to do.          
        } else {

            // permission denied, boo! Disable the
            // functionality that depends on this permission.
            Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
        }
        return;
    }

    // other 'case' lines to check for other
    // permissions this app might request
}

}

Comments