![](/img/trans.png)
[英]What happens when a synchronized method is called by a thread via another class?
[英]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.