0

У меня есть два слушателя BroadcastReceiverSms и BroadcastReceiverCall которые отслеживают когда на телефон ЗВОНЯТ и приходит СМС и выводят оповещение с вибрацией. Когда приложение работает в фоне то оповещение по середине экрана при получении СМС работает корректно, но когда звонят не работает. Так-же когда я закрываю приложение то оповещение не появляется при СМС и при ЗВОНКЕ, хотя по идее BroadcastReceiver работает.

Манифест

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

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service
            android:name="detector.sakuraso13.Service.ServiceMain"
            android:enabled="true"
            android:exported="true"></service>

        <receiver
            android:name="detector.sakuraso13.Broadcaster.MyReceiverCall"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:priority="999">
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="detector.sakuraso13.Broadcaster.MyReceiverSms"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="999">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                <action android:name="android.provider.Telephony.SMS_DELIVER" />
            </intent-filter>
        </receiver>

        <activity android:name="detector.sakuraso13.Main.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MyReceiverCall

public class MyReceiverCall extends BroadcastReceiver {
    private static final String TAG = "MyReceiverCall";
    private static final String ACTION = "android.intent.action.PHONE_STATE";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getAction() != null) {
            String action = intent.getAction();
            if (action.equals(ACTION)) {

                String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        // логика
                        Intent intentService = new Intent(context, ServiceMain.class);
                        intentService.putExtra("type", "call");
                        intentService.putExtra("content", call);
                        context.startService(intentService);

                }
                }
            }
        }

MyReceiverSms

public class MyReceiverSms extends BroadcastReceiver {
    private static final String TAG="MyReceiverSms";
    private static final String ACTION="android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent !=  null && intent.getAction()!=null) {
            String action = intent.getAction();
            if (action.equals(ACTION)) {
                    Intent intentService=new Intent(context, ServiceMain.class);
                    intentService.putExtra("type","sms");
                    intentService.putExtra("content",sms);
                    context.startService(intentService);


            }
        }
    }

}

ServiceMain

public class ServiceMain extends Service {
    private static WindowManager windowManager;
    private static ViewGroup windowLayout;
    private final String TAG = "ServiceMain";

    public ServiceMain() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showWindow("heh");
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }



    private void showWindow(String phone) {
        closeWindow();
        Context context = getApplicationContext();
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                        ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                        : WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER;
        windowLayout = (ViewGroup) layoutInflater.inflate(R.layout.info, null);
        TextView textViewNumber=(TextView) windowLayout.findViewById(R.id.textViewNumber);
        Button buttonClose=(Button) windowLayout.findViewById(R.id.buttonClose);
        textViewNumber.setText(phone);
        buttonClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeWindow();
            }
        });
        windowManager.addView(windowLayout, params);long mills = 1000L;
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if(vibrator!=null) {
            if (vibrator.hasVibrator()) {
                vibrator.vibrate(mills);
            }
        }

    }

    private void closeWindow() {
        if (windowLayout !=null){
            windowManager.removeView(windowLayout);
            windowLayout =null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

}
2
  • Покажите код регистрации ресивера
    – Barmaley
    9 окт 2019 в 6:04
  • @Barmaley registerReceiver(new MyReceiverCall(), new IntentFilter(Intent.ACTION_SCREEN_ON)); registerReceiver(new MyReceiverSms(),new IntentFilter(Intent.ACTION_SCREEN_ON));
    – sakuraso13
    9 окт 2019 в 16:45

1 ответ 1

-1

Вам не нужно программно регистрировать ресивер в коде. Скорее всего, вы регистрируете его в Activity.onStart() и снимаете регистрацию в Activity.onStop()

У вас ресивер уже зарегистрирован в манифесте, поэтому это лишняя операция.

Кстати, у меня в коде немного не так:

  <!-- SMS receiver -->
    <receiver
        android:name=".SmsReceiver"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BROADCAST_SMS" >
        <intent-filter android:priority="2147483647" > <!-- 999 is highest system priority, so it's hack 2147483647 -->
            <action android:name="android.provider.Telephony.SMS_RECEIVED" /> <!-- pre kitkat action -->
            <action android:name="android.provider.Telephony.SMS_DELIVER" /> <!-- kitkat action -->
        </intent-filter>
    </receiver>
2
  • Можете подсказать пожалуйста, а как вы реализовываете для звонков?
    – sakuraso13
    10 окт 2019 в 16:21
  • Звонки никогда не перехватывал - не было такой задачи.
    – Barmaley
    11 окт 2019 в 5:45

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.