当前位置: 首页 > 知识库问答 >
问题:

接口不能强制转换(ClassCastException:AlarmReceiver不能强制转换为AlarmReceiver$OnAlarMover)

燕英逸
2023-03-14
public class AlarmReceiver extends BroadcastReceiver {
  public AlarmReceiver() {
  }

  @Override
  public void onReceive(Context context, Intent intent) {

    ...

    OnAlarmOver onAlarmOver = (OnAlarmOver) context; //<--error
    onAlarmOver.OnAlarmOverText("Alarm stop");        
  }

  public interface OnAlarmOver {
    public void OnAlarmOverText(String overText);
  }
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements AlarmReceiver.OnAlarmOver {

  ...

  public void OnAlarmOverText(String overText){
    alarm_text.setText(overText);
  }
}

对不起,我的英语很差。

共有1个答案

齐晟
2023-03-14

您正试图将上下文强制转换为OnAlarMover。当然,这是行不通的。我想你想在你的应用程序中的其他地方捕捉一个广播发射。

1)您需要定义您的广播。然后,在您的活动中,您应该注册它。例如:

private BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            if(intent.getAction().equals(SearchService.NOTIFICATION)){

            }
        }
    }
};

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(receiver, new IntentFilter(SearchService.NOTIFICATION));
}

记住在pause方法中取消注册

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}
private void publishResults(Search result) {
    Intent intent = new Intent(NOTIFICATION);
    intent.putExtra(RESULT, result);
    sendBroadcast(intent);
    success = true;
}
 类似资料: