java - Android java.lang.RuntimeException : Error receiving broadcast Intent

标签 java android exception service broadcast

我的应用程序一启动就崩溃了,但我不知道为什么。我有一个Service,用作计时器来计算自计时器启动以来的秒数,然后将其传递回我的MainActivity

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "BroadcastTest";
    private Intent intent;

    private Chronometer timer;
    private Button start;
    private Button stop;
    private EditText hourlyRate;
    private TextView money;
    private long timeWhenStopped = 0;
    private double moneyEarned;
    private double secondsRate;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        timer = (Chronometer) findViewById(R.id.chronometer);
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        hourlyRate = (EditText) findViewById(R.id.hourlyRate);
        money = (TextView) findViewById(R.id.money);

        intent = new Intent(this, Timer.class);

          start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startService(new Intent(MainActivity.this, Timer.class));
                timer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
                timer.start();

            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timeWhenStopped = timer.getBase() - SystemClock.elapsedRealtime();
                timer.stop();
            }
        });

        timer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener()
        {
            @Override
            public void onChronometerTick(Chronometer chronometer){
                long timeElapsed = SystemClock.elapsedRealtime() - timer.getBase();
                int seconds = (int) timeElapsed / 1000;

                double hrlyRate = Double.parseDouble(hourlyRate.getText().toString());
                secondsRate = (hrlyRate / 60) / 60;

                moneyEarned = secondsRate * seconds;

                double displayMoney = Math.round(moneyEarned * 100.0)/100.0;

                Log.d("hours",Long.toString(seconds));

                money.setText("$"+Double.toString(displayMoney));

            }
        });

        }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateUI(intent);
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        startService(intent);
        registerReceiver(broadcastReceiver, new IntentFilter(Timer.BROADCAST_ACTION));
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        stopService(intent);
    }

    private void updateUI(Intent intent) {
        String counter = intent.getStringExtra("counter");
        Log.d("SERVICE_SECONDS", counter);
    }
}

Timer.java:

public class Timer extends Service {

    private static final String TAG = "BroadcastService";
    public static final String BROADCAST_ACTION = "b.calvin.com.dirtymoney";
    private final Handler handler = new Handler();
    Intent intent;
    int counter = 0;

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            countSeconds();
            handler.postDelayed(this, 1000); // 1 second
        }
    };

    @Override
    public void onCreate()
    {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);
    }

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

        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 0); // 1 second

        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
            return START_STICKY;
        }

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

    private void countSeconds() {
        Log.d(TAG, Integer.toString(++counter));
        sendBroadcast(intent);
    }
}

错误:

FATAL EXCEPTION: main
Process: b.calvin.com.dirtymoney, PID: 3348
java.lang.RuntimeException: Error receiving broadcast Intent { act=b.calvin.com.dirtymoney flg=0x10 } in b.calvin.com.dirtymoney.MainActivity$4@bf337ff
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:891)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at b.calvin.com.dirtymoney.MainActivity.updateUI(MainActivity.java:113)
at b.calvin.com.dirtymoney.MainActivity.access$600(MainActivity.java:20)
at b.calvin.com.dirtymoney.MainActivity$4.onReceive(MainActivity.java:93)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:881)
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

最佳答案

似乎您忘记将 counter 变量放入 Intent 中,因此您将 null 传递给 Log.d () 作为消息,导致 NullPointerException

这样的事情应该有效:

private void countSeconds() {
    Log.d(TAG, Integer.toString(++counter));

    Intent counterIntent = new Intent(BROADCAST_ACTION);
    counterIntent.putExtra("counter", counter);

    sendBroadcast(counterIntent);
}

此外,计数器是一个 int,因此您应该调用 getIntExtra() 而不是 getStringExtra():

private void updateUI(Intent intent) {
    int counter = intent.getIntExtra("counter");
    Log.d("SERVICE_SECONDS", Integer.toString(counter));
}

关于java - Android java.lang.RuntimeException : Error receiving broadcast Intent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39140814/

相关文章:

android - 如何使 ImageView 在工具栏中居中?

android - 如何将文件存储在 SD 卡上(外部)

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

c++ - 如何捕获 C++/Windows 中的每个异常?

java - 自动重新加载属性文件

android - 如何在 MapBox 上显示房屋号码?

java - 在 Android 的 FrameLayout 上添加 Fragment

c++ - 使用 vs typedef pointer-to-noexcept-function 不一致

java - 我正在测试一个变量,并且不断收到 android.widget.EditText@

java - AWS S3 Java SDK 不将文件复制到文件夹