【问题标题】:Can't do heavy work on broadcast receiver which is inside the Service不能在服务内的广播接收器上做繁重的工作
【发布时间】:2020-08-11 02:58:53
【问题描述】:

我创建了一个Broadcast Receiver,它在Service Class 里面(由于Android Broadcast receiver 限制Broadcast receiver 在一段时间后停止,所以我创建了Background Service,前景为Service Notification Android 限制奥利奥=)。这个Broadcast Receiver 监听电话呼叫状态的变化IDLE、OFFHOOK、RINGING。根据电话通话状态更改(如果通话结束),我在光标中获取最后通话详细信息并将该详细信息发送到 Firebase Realtime Database。在我对 saveDatafromCursor() 内部的 PhoneStateListener Class 方法发表评论(//)之前,一切都运行良好。 (我在保存数据方法之前写了一条 Toast 消息)。它工作得很好。我的服务很好。但是如果我在通话结束后取消注释我的saveDatafromCursor() 方法。我的服务停止(通知图标和 toast 消息停止。我在真实设备中签入)。 在没有实现服务的情况下,我将数据发送到运行良好的 Firebase,如果我尝试将数据保存到 Firebase,为什么我的服务会停止?

服务类

public class HammerService extends Service {

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

        IntentFilter ifilter = new IntentFilter();
        ifilter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);

        registerReceiver(receiver, ifilter);

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String input = intent.getStringExtra("inputExtra");
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Hammer Service")
                .setContentText(input)
                .setSmallIcon(R.drawable.ic_android)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);

        //do heavy work on a background thread
        //stopSelf();
        return START_NOT_STICKY;

    }


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

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

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            String action = intent.getAction();
            if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
                //action for sms received
            }
            else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
                runfirstTime(context,intent);
            }
        }
    };

    private void runfirstTime(Context context, Intent intent) {
        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        MyPhoneStateListener customPhoneListener = new MyPhoneStateListener();

        telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        Bundle bundle = intent.getExtras();
        String phone_number = bundle.getString("incoming_number");

        String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
        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;
        }

        if (phone_number == null || "".equals(phone_number)) {
            return;
        }

        customPhoneListener.onCallStateChanged(context, state, phone_number);
    }
}

PhoneStateListener 类

public class MyPhoneStateListener extends PhoneStateListener {

    private static int lastState = TelephonyManager.CALL_STATE_IDLE;
    private static Date callStartTime;
    private static boolean isIncoming;

    static boolean calledAlready = false;

    private DatabaseReference databaseReference;
    private Context ctx;


    public void onCallStateChanged(Context context, int state, String phoneNumber) {
        if (lastState == state) {
            //No change, debounce extras
            return;
        }

        ctx = context;

        System.out.println("Number inside onCallStateChange : " + phoneNumber);

        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                isIncoming = true;
                callStartTime = new Date();

                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                if (lastState != TelephonyManager.CALL_STATE_RINGING) {
                    isIncoming = false;
                    callStartTime = new Date();

                }
                break;

            case TelephonyManager.CALL_STATE_IDLE:
                //Went to idle-  this is the end of a call.  What type depends on previous state(s)
                if (lastState == TelephonyManager.CALL_STATE_RINGING) {
                    //Ring but no pickup-  a miss
                    waitforlastcalllog();

                } else if (isIncoming) {

                    //  Toast.makeText(context, "Incoming " + phoneNumber + " Call time " + callStartTime  , Toast.LENGTH_SHORT).show();

                    waitforlastcalllog();
                } else {

                    //  Toast.makeText(context, "outgoing " + phoneNumber + " Call time " + callStartTime +" Date " + new Date() , Toast.LENGTH_SHORT).show();

                    waitforlastcalllog();
                }

                break;
        }

        lastState = state;
    }

    private void waitforlastcalllog() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //String deviceMan = android.os.Build.MANUFACTURER;
                String deviceMan = Build.MANUFACTURER;

                String deviceName=deviceMan.toLowerCase();

                if(deviceName.equals("samsung"))
                {
                   // Toast.makeText(ctx, "dvv "+deviceMan, Toast.LENGTH_SHORT).show();
                    getCallLogs("samsung");
                }
                else
                {
                    getCallLogs("other");
                }


            }
        }, 500);

    }

    private void getCallLogs(String devicename) {

        ContentResolver cr = ctx.getContentResolver();
        if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Cursor c = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, null);

        if (c != null) {

            if(devicename.equals("samsung"))
            {
                if (c.moveToFirst()) { //starts pulling logs from last - you can use moveToFirst() for first logs
                    getCallDetails(c);
                }
            }else
            {
                if (c.moveToLast()) { //starts pulling logs from last - you can use moveToFirst() for first logs
                    getCallDetails(c);
                }
            }

            c.close();
        }
    }

    private void getCallDetails(Cursor c)
    {
        int totalCall=1;

        for (int j = 0; j < totalCall; j++) {

            String call_id = c.getString(c.getColumnIndexOrThrow(CallLog.Calls._ID));
            String phNumber = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
            String callDate = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DATE));
            String callDuration = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DURATION));
            Date dateFormat= new Date(Long.valueOf(callDate));
            String callDayTimes = String.valueOf(dateFormat);
            String callerName = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME));


            String direction = null;
            switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(CallLog.Calls.TYPE)))) {
                case CallLog.Calls.OUTGOING_TYPE:
                    direction = "OUTGOING";
                    break;
                case CallLog.Calls.INCOMING_TYPE:
                    direction = "INCOMING";
                    break;
                case CallLog.Calls.MISSED_TYPE:
                    direction = "MISSED";
                    break;
                case CallLog.Calls.VOICEMAIL_TYPE:
                    direction = "VOICEMAIL_TYPE";
                    break;
                case CallLog.Calls.REJECTED_TYPE:
                    direction = "REJECTED_TYPE";
                    break;
                case CallLog.Calls.BLOCKED_TYPE:
                    direction = "BLOCKED_TYPE";
                    break;
                case CallLog.Calls.ANSWERED_EXTERNALLY_TYPE:
                    direction = "ANS EXT TYPE";
                    break;
                default:
                    break;
            }

            c.moveToPrevious(); // if you used moveToFirst() for first logs, you should this line to moveToNext

            Toast.makeText(ctx, phNumber + callDuration + callDayTimes + direction +callerName , Toast.LENGTH_LONG).show(); // you can use strings in this line
            saveDatafromCursor(phNumber,callDuration,callDayTimes,direction,callerName);
        }
    }


    private void saveDatafromCursor(String phNumber, String callDuration, String callDayTimes, String direction,String callername)
    {
        ModelCursor mc=new ModelCursor();

        mc.setPhoneNumber(phNumber);
        mc.setCallDuration(callDuration);
        mc.setCallDayTimes(callDayTimes);
        mc.setDirection(direction);

        if(callername==null)
        {
            callername="Not in Contacts";
        }

        mc.setCallUsername(callername);


        if (!calledAlready) {
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
            calledAlready = true;
        }

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        databaseReference = database.getInstance().getReference().child("Call-Details-X");
        String key = databaseReference.push().getKey();

        String android_id = Settings.Secure.getString(ctx.getContentResolver(),
                Settings.Secure.ANDROID_ID);

        Date date=new Date();

        SimpleDateFormat timeStampFormatsearch = new SimpleDateFormat("dd-yyyy-MM");
        String dateofcall = timeStampFormatsearch.format(date);


        databaseReference.child(android_id).child(dateofcall).child(key).setValue(mc).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {

            }
        });
    }

}

Logcat - 错误

2020-08-12 10:03:33.217 5151-5151/com.fooding.callhammer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.fooding.callhammer, PID: 5151
    com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
        at com.google.firebase.database.FirebaseDatabase.assertUnfrozen(com.google.firebase:firebase-database@@17.0.0:316)
        at com.google.firebase.database.FirebaseDatabase.setPersistenceEnabled(com.google.firebase:firebase-database@@17.0.0:284)
        at com.fooding.callhammer.MyPhoneStateListener.saveDatafromCursor(MyPhoneStateListener.java:214)
        at com.fooding.callhammer.MyPhoneStateListener.getCallDetails(MyPhoneStateListener.java:191)
        at com.fooding.callhammer.MyPhoneStateListener.getCallLogs(MyPhoneStateListener.java:138)
        at com.fooding.callhammer.MyPhoneStateListener.access$000(MyPhoneStateListener.java:26)
        at com.fooding.callhammer.MyPhoneStateListener$1.run(MyPhoneStateListener.java:104)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2020-08-12 10:03:33.446 2016-2122/system_process E/InputDispatcher: channel '276f02e com.fooding.callhammer/com.fooding.callhammer.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2020-08-12 10:03:36.556 2016-2197/system_process E/TaskPersister: File error accessing recents directory (directory doesn't exist?).
2020-08-12 10:03:48.799 2016-2041/system_process E/memtrack: Couldn't load memtrack module
2020-08-12 10:03:49.499 2016-2048/system_process E/BatteryExternalStatsWorker: no controller energy info supplied for wifi
2020-08-12 10:04:00.018 2016-2041/system_process E/memtrack: Couldn't load memtrack module

【问题讨论】:

  • 请检查 logcat 是否有错误、异常。不要过滤 logcat,否则你可能会错过一些重要的东西。您需要确定崩溃的原因和原因。
  • 谢谢您,先生,您的回复就是我的回答。在我在真实设备上运行它之前,我认为由于广播接收器的繁重工作而终止了服务,但问题是 firebase 离线功能,我的应用程序崩溃了。现在我初始化了,很好stackoverflow.com/a/37766261/5359340,非常感谢你的回复

标签: android firebase-realtime-database service broadcastreceiver phone-state-listener


【解决方案1】:

来自文档:服务在其托管进程的主线程中运行;除非您另外指定,否则该服务不会创建自己的线程并且不会在单独的进程中运行。您应该在服务内的单独线程上运行任何阻塞操作以避免应用程序无响应 (ANR) 错误。我认为这就是你不能在 Service 类中做“繁重”工作的原因。我没有看你的代码,但你可以做两件事:

1.) 在创建时在服务内创建新线程并做“繁重的工作”(不要忘记停止它)。 https://developer.android.com/guide/components/services

2.) 扩展 JobIntentService 类,试一试。然后覆盖函数 onHandleWork(intent),开始“繁重”的工作。 https://developer.android.com/reference/androidx/core/app/JobIntentService

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多