0

我有一个问题BroadcastRecievers。我正在注册他们,但他们没有收到广播。我的目标是创建一个SMS发送位置数据的自动回复器。这是我的清单:

<?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>

这是我的主要活动:

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");
            }
        });
    }

}

这是我的广播接收器:

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;
        }
    }

}

这是我的服务:

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){}
    }
}

谢谢!(我正在第二代 Moto G 上测试这个)

4

1 回答 1

0

在清单中注册接收器。例子。

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

此外,检查手机 API 级别是否为 6.0 或更高,然后您需要在运行时文档中请求权限

在创建时添加此代码

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

在 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
}

}

于 2016-10-09T16:33:52.030 回答