Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

broadcastreceiver - android broadcast receiver (call and sms received) not working in android nougat

android call and SMS broadcast receiver working perfectly till marshmallow 6.0, but in android nougat , it is not working when app is closed, and when app is in background, then its working fine in android nougat(N). please can anyone help me for this issue.

public class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
        savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
        Log.d("t savedNumber", savedNumber);
        return;
    }else{
        String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
        String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

        int state = 0;
        if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
            state = TelephonyManager.CALL_STATE_IDLE;
        }
        else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
            state = TelephonyManager.CALL_STATE_OFFHOOK;
        }
        else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
            state = TelephonyManager.CALL_STATE_RINGING;
        }

        Log.d("t incoming Number", number+" state: "+state+ " stateStr: "+stateStr);

        onCallStateChanged(context, state, number);
    }
 }
}

permisssion added in mainfest file

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

registering receiver

     <receiver android:name=".Receiver.CallReceiver ">
        <intent-filter android:priority="100">
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
        <intent-filter>
            <action    android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
    </receiver>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this service ..!

SMS Observer

 package com.demo.service;

import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class SmsObserver extends ContentObserver {

    String TAG =SmsObserver.class.getSimpleName();

    static final Uri SMS_STATUS_URI = Uri.parse("content://sms");
    private Context mContext;
    private String contactId = "", contactName = "";
    private String smsBodyStr = "", phoneNoStr = "";
    private long smsDatTime = System.currentTimeMillis();

    public SmsObserver(Handler handler, Context ctx) {
        super(handler);
        mContext = ctx;
    }

    public boolean deliverSelfNotifications() {
        return true;
    }

    public void onChange(boolean selfChange) {
        try {
            Log.e("Info", "Notification on SMS observer");
            Cursor sms_sent_cursor = mContext.getContentResolver().query(SMS_STATUS_URI, null, null, null, null);
            if (sms_sent_cursor != null) {
                if (sms_sent_cursor.moveToFirst()) {
                    String protocol = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("protocol"));
                    Log.e("Info", "protocol : " + protocol);
                    //for send  protocol is null
                    if (protocol == null) {
                        /*
                        String[] colNames = sms_sent_cursor.getColumnNames();
                        if(colNames != null){
                            for(int k=0; k<colNames.length; k++){
                                Log.e("Info","colNames["+k+"] : " + colNames[k]);
                            }
                        }
                        */
                        int type = sms_sent_cursor.getInt(sms_sent_cursor.getColumnIndex("type"));
                        Log.e("Info", "SMS Type : " + type);
                        // for actual state type=2
                        if (type == 2) {
                            Log.e("Info", "Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("_id")));
                            Log.e("Info", "Thread Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("thread_id")));
                            Log.e("Info", "Address : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")));
                            Log.e("Info", "Person : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("person")));
                            Log.e("Info", "Date : " + sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date")));
                            Log.e("Info", "Read : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("read")));
                            Log.e("Info", "Status : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("status")));
                            Log.e("Info", "Type : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("type")));
                            Log.e("Info", "Rep Path Present : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("reply_path_present")));
                            Log.e("Info", "Subject : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("subject")));
                            Log.e("Info", "Body : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")));
                            Log.e("Info", "Err Code : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("error_code")));

                            smsBodyStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")).trim();
                            phoneNoStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")).trim();
                            smsDatTime = sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date"));

                            Log.e("Info", "SMS Content : " + smsBodyStr);
                            Log.e("Info", "SMS Phone No : " + phoneNoStr);
                            Log.e("Info", "SMS Time : " + smsDatTime);

                        }
                    }
                }
            } else
                Log.e("Info", "Send Cursor is Empty");
        } catch (Exception sggh) {
            Log.e("Error", "Error on onChange : " + sggh.toString());
        }
        super.onChange(selfChange);
    }//fn onChange


}//End of class SmsObserver

Phone State service

package com.demo.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


public class PhoneStateService extends Service {

    String TAG = PhoneStateService.class.getSimpleName();

    boolean isMissedCall = false;
    boolean isRingingCall = false;
    boolean isRingingCallOne = false;

    String onOff;
    String callerID;
    String callerIDOne;
    String[] cIds;
    String[] cIdsOne;

    private CallStateListener mCallStateListener = new CallStateListener();
    private TelephonyManager mTelephonyManager;
    private int mCallState;

    @Override
    public void onCreate() {
        super.onCreate();
        mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        mCallState = mTelephonyManager.getCallState();
        mTelephonyManager.listen(mCallStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public void onDestroy() {
        Log.d("onDestroy", "onDestroy");
        mTelephonyManager.listen(mCallStateListener, PhoneStateListener.LISTEN_NONE);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null; //-- not a bound service--
    }

    private final class CallStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            String getSimSerialNumber = mTelephonyManager.getSimSerialNumber();
            String mPhoneNumber = mTelephonyManager.getLine1Number();


            Log.d("number", "getSimSerialNumber : " + getSimSerialNumber);
            Log.d("number", "mPhoneNumber : " + mPhoneNumber);

            Log.d("number", "number : " + incomingNumber+" callstatelistner : "+state + "  "+Consts.number);

            onOff = SharedPreferenceUtil.getString("onOff","");

            callerID = SharedPreferenceUtil.getString("callerID","");

            callerIDOne = SharedPreferenceUtil.getString("callerIDOne","");

            cIds = new String[0];

            cIdsOne = new String[0];
            Log.d(TAG,"callerID : "+ callerID);
            Log.d(TAG,"callerIDOne : "+ callerIDOne);
            if (!callerID.equals("")) {
                try {
                    callerID = callerID.substring(0, callerID.length() - 1);
                    cIds = callerID.split(",");
                    Log.d(TAG,"callerID  :: "+ cIds.toString());
                    Log.d(TAG,"callerID  :: "+ cIds.length);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (!callerIDOne.equals("")) {
                try {
                    callerIDOne = callerIDOne.substring(0, callerIDOne.length() - 1);
                    cIdsOne = callerIDOne.split(",");

                    Log.d(TAG,"callerIDOne  :: "+ cIdsOne.toString());
                    Log.d(TAG,"callerIDOne  :: "+ cIdsOne.length);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            int OFFHOOK = TelephonyManager.CALL_STATE_OFFHOOK;
            int IDLE = TelephonyManager.CALL_STATE_IDLE;
            int RINGING = TelephonyManager.CALL_STATE_RINGING;

// my change
            mCallState = state;
//            Log.v("state","-- "+state+  "  --- "+TelephonyManager.CALL_STATE_IDLE+" - "+TelephonyManager.CALL_STATE_OFFHOOK+"  - "+TelephonyManager.CALL_STATE_RINGING);
            Log.v("state","-- "+state+  "  --- "+IDLE+" - "+OFFHOOK+"  - "+RINGING);
            if (state == 0){
                Log.d(TAG, "state ....0");
                if (state == OFFHOOK) {
                    Log.d("state", "idle --> off hook = new outgoing call"+ Consts.number);
                    // idle --> off hook = new outgoing call
                    //triggerSenses(Sense.CallEvent.OUTGOING);

                    callStateOffhoof(incomingNumber);
                } else if (state == RINGING) {
                    Log.d("state", "idle --> ringing = new incoming call"+Consts.number);
                    // idle --> ringing = new incoming call
                    //triggerSenses(Sense.CallEvent.INCOMING);
                    callStateRinging(incomingNumber);
                }else if (state == IDLE) {
                    Log.d(TAG, "state ....IDLE");
                    Log.d("state", "ringing --> idle = missed call"+Consts.number);
                    // ringing --> idle = missed call
                    //triggerSenses(Sense.CallEvent.MISSED);
                    callStateIdeal(incomingNumber);
                }
            }else if (state == 1){
                Log.d(TAG, "state ....1");
                if (state == OFFHOOK) {
                    Log.d("state", "ringing --> off hook = received"+Consts.number);
                    // ringing --> off hook = received
                    //triggerSenses(Sense.CallEvent.RECEIVED);
                    callStateOffhoof(incomingNumber);
                } else if (state == IDLE) {
                    Log.d("state", "ringing --> idle = missed call"+Consts.number);
                    // ringing --> idle = missed call
                    //triggerSenses(Sense.CallEvent.MISSED);
                    callStateIdeal(incomingNumber);
                }else if (state == RINGING)  {
                    Log.d("state", "idle --> ringing = new incoming call"+Consts.number);
                    // idle --> ringing = new incoming call
                    //triggerSenses(Sense.CallEvent.INCOMING);
                    callStateRinging(incomingNumber);
                }
            }else if (state == 2){
                Log.d(TAG, "state ....2");
                if (state == IDLE) {
                    Log.d("state", "off hook --> idle  = disconnected"+Consts.number);
                    // off hook --> idle  = disconnected
                    //triggerSenses(Sense.CallEvent.ENDED);
                    callStateIdeal(incomingNumber);
                } else if (state == RINGING) {
                    Log.d("state", "off hook --> ringing = another call waiting"+Consts.number);
                    // off hook --> ringing = another call waiting
                    //triggerSenses(Sense.CallEvent.WAITING);
                    callStateRinging(incomingNumber);
                }else if(state==OFFHOOK)
                {
                    String nm = Consts.number;
                    if (!nm.isEmpty()){
                        callStateOffhoof(nm);
                    }else {
                        callStateOffhoof(incomingNumber);
                    }

                }
                Log.d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...