2016-10-09 3 views
0

BroadcastRecievers에 문제가 있습니다. 나는 그들을 등록하고 있지만 방송을받지 못하고있다. 내 목표는 위치 데이터를 보낼 SMS 자동 응답을 만드는 것입니다. 여기 브로드 캐스트 수신자가 작동하지 않음, SMS를 사용하여 Moto G에서 테스트 중

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

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

} 

것은 내 BroadcastReciever입니다 :

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

감사 : 여기

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

} 

내 서비스 당신!(나는 이것을 제 2 세대 Moto G에서 테스트하고있다.)

+0

작동하지 않습니까? 아니면 전화를 다시 시작해야합니까? –

답변

0

등록 수신기 목록. 예. 당신이에서 onCreate

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

재정 활동

에서이 방법을이 코드를 Doc

런타임에 권한을 요청 추가해야 다음 6.0 이상 인 경우

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

또한, 전화 API 레벨을 확인

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

}

+0

하지만 저는 이미 동적으로 등록했습니다. 그리고 네, marshmallow – Vicky

+0

을 실행하고 런타임 권한을 요청했기 때문에 문서를 읽을 것입니까? 그것없이 (등록 수신기 이전에) 당신은 그것을 얻을 수 없습니다 ... – Opiatefuchs

+0

다음 문제는 당신에게 허가가 없습니다. –