MyReceiver.Java
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Log.i("MyReceiver", "MyAction received!");
}
}
AndroidManifest.xml
(application
タグの下)
<receiver Android:name=".MyReceiver">
<intent-filter>
<action Android:name="MyAction" />
</intent-filter>
</receiver>
MainActivity.Java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendBroadcast(new Intent("MyAction"));
}
}
MyReceiver.onReceive
メソッドはトリガーされません。私は何か見落としてますか?
Android 8。
次に、明示的なIntent
を使用する必要があります。これは、次のような受信者を識別するものです。
sendBroadcast(new Intent(this, MyReceiver.class).setAction("MyAction"));
Broacastの制限 in Android 8リリースドキュメント。
In Android 8 onwords
例:
private void triggerBroadCast(String firstFavApp, String secondFavApp) {
Intent intent = new Intent("FavAppsUpdated");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.putExtra("FIRST_FAV_APP", firstFavApp);
intent.putExtra("SECOND_FAV_APP", secondFavApp);
intent.setComponent(new
ComponentName("com.Android.systemui",
"com.Android.systemui.statusbar.phone.FavAppsChanged"));
Log.i(TAG, "Trigger Fav Apps" + firstFavApp + " " + secondFavApp);
favouriteContract.getAppContext().sendBroadcast(intent);
}
以下Android 8
void broadCastParkingStates(Context context) {
Intent intent = new Intent("ReverseCameraStates");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.putExtra("PARKING_GUIDE", ReverseCameraPreference.getParkingGuide(context));
intent.putExtra("PARKING_SENSOR", ReverseCameraPreference.getParkingSensor(context));
intent.putExtra("TRAJECTORY", ReverseCameraPreference.getTrajectory(context));
Log.i("BootCompletedReceiver", "Sending Reverse Camera settings states BaordCast");
Log.i("BootCompletedReceiver", "States Parking:Sensor:Trajectory="
+ intent.getExtras().getBoolean("PARKING_GUIDE")
+ ":" + intent.getExtras().getBoolean("PARKING_SENSOR")
+ ":" + intent.getExtras().getBoolean("TRAJECTORY")
);
context.sendBroadcast(intent);
}
メインアクティビティコードを次のように変更します。-Intent intent =new Intent(this,MyReceiver.class); intent.setAction("MyAction"); sendBroadcast(intent);
コトリンで
val intent = Intent(this, MyBroadCastReceiver::class.Java)
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.action = "my.custom.braodacat"
sendBroadcast(intent)