简体   繁体   中英

Logs/logcat not working in BroadcastReceiver

I have a BroadcastReceiver and it there is some problem. The Toast message is showing, and the logcat message is appearing with the command line logcat tool, but not in the Android studio Logcat display. Why? I have already tried android:debuggable="true" and anything has not changed.

public class AlarmReceiver extends BroadcastReceiver {
        private String filePath;
        private Ringtone ringtone;

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("RECEIVE", "");
            Bundle extras = intent.getExtras();
            if (extras == null) {
                filePath = null;
            } else {
                filePath= extras.getString("filePath");
            }
            Log.d("Filepath in receiver", filePath);
            ringtone = RingtoneManager.getRingtone(context, Uri.parse(filePath));
            ringtone.play();
            Toast.makeText(context, "Fooo", Toast.LENGTH_LONG).show();
            //   setRingsong(context, filePath);
        }
    }

Try this on a shell. adb logcat D |grep RECEIVE adb program can be found on your sdk sdk tools(platform-tools) this is the program the actual debugger use when retreiving the logs.

The "D" parameter indicates that it will show "debug" logs, this complements the android:debuggable="true" setting if you wish to print logs while debugging (remember these are two different things, printing logs with the Log object and setting "android.debuggable = true",check this link for more information about debugging with AndroidStudio). Otherwise, try using Log.e function instead of Log.d. Log.e is usually for errors, in this case for testing purposes you can use it and ensure your logs will always be displayed, due to error logs having a higher priority thatn debug logs.

  1. ( optional step ) At first create a static/const variable named TAG:

     const val TAG = "aaa"
  2. In Logcat window -> Filters DropDown -> Edit Filter Configuration:

在此处输入图片说明

  1. Then in Log Tag: field enter the name chosen in the first step:

2

You can now log what you want in BroadcastReceiver or anywhere else in your project:

class BroadcastReceiver : BroadcastReceiver() {

  override fun onReceive(context: Context?, intent: Intent?) {
      context ?: return

      Log.d(TAG, intent?.action!!)
  }
}

and the result will be like:

3

The problem is that the tag should not be all uppercase. If you use "receive" or "Receive", it will be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM