Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在我的活动中调用广播接收器,以便当我单击按钮时它将激活?_Android - Fatal编程技术网

Android 如何在我的活动中调用广播接收器,以便当我单击按钮时它将激活?

Android 如何在我的活动中调用广播接收器,以便当我单击按钮时它将激活?,android,Android,我为传入呼叫创建了广播接收器,并在清单文件中注册了接收器。我是新手,所以我不明白在我的主要活动中如何在我的按钮上调用它 public class CallReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String state = intent.getStringExtra(TelephonyManager

我为传入呼叫创建了广播接收器,并在清单文件中注册了接收器。我是新手,所以我不明白在我的主要活动中如何在我的按钮上调用它

public class CallReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        String msg = "Phone state changed to " + state;

        if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
                String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            msg += ". Incoming number is " + incomingNumber;

            // TODO This would be a good place to "Do something when the phone rings" ;-)
            }
            Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }
}

如果在清单文件中注册广播接收器,则每当事件发生时,它将自动被触发。 除此之外,请单击按钮进行广播接收器注册:

btn.setOnClickListener{
   registerReceiver()
}

override fun onStop(){
   fun registerReceiver()
}

private fun registerReceiver(){
  //Do the registration here
}

private fun fun registerReceiver() {
   // Unsubscribe receiver
}

有关更多信息:


你可以用这个注册接收者,我是在我的服务课上注册的

ServiceInstance.registerReceiver(receiverName, choice "if any action");
您可以使用此…注销收件人

ServiceInstance.unregisterReceiver(receiverName);

若你们在清单中注册广播接收器,它将在应用程序启动时自动启动,但在Android Oreo清单注册后,接收器将无法工作。而是使用上下文注册的接收器。