繁体   English   中英

当从另一个 class 使用 synchronized() 调用 notify() 方法时,它没有被调用形式

[英]notify() method not been called form when calling it from another class with synchronized()

我正在尝试在电池电量低于 %10 时发出通知。

这是我的通知 class 位于 MainActivity.java

    public void notify(View view) {
        String title = "Warning! low battery";
        String text = "Please plug your mobile device to a charger";

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_qs_battery_saver)
                .setContentTitle(title)
                .setContentText(text)
                .setContentIntent(pendingIntent)
                .build();

        notificationManager.notify(notificationID++, notification);
    }

我正在尝试从 BatteryReceiver class 发射它:

package com.michal.ex2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;
import android.view.View;

public class BatteryReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {

            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatus = context.registerReceiver(null, ifilter);
            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
            int percent = (level * 100) / scale;

            int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            boolean isPlugged;
            isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;

            if ((percent == 10) && !isPlugged) {
                Log.d("mylog", "low battery");
                //notify();
                synchronized(mActivity){
                    mActivity.notify();
            }

        }

    }
}

首先,我尝试从 MainActivity 调用通知,但应用程序崩溃并出现错误: java.lang.IllegalMonitorStateException: object not locked by thread before notify()

我已经搜索了一个解决方案,发现我需要锁定通知,所以我尝试使用 synchronized() 调用它:

synchronized(mActivity){
          mActivity.notify();

但什么也没发生。 电池接收器工作正常(我得到了正确的日志消息),但没有调用 notify()。

也许您调用的 function 不是 MainActivity.notify(View view) 而是Object.notify() 因此什么也没有发生。 给出适当的 function 参数。

mActivity.notify(null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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