J'essaie d'implémenter un BroadCastReceiver simple avec une action personnalisée qui fait apparaître un toast dans la méthode onReceive()
du récepteur mais cela ne fonctionne pas pour une raison mystérieuse !!Android BroadCastReceiver ne fonctionne pas avec des actions personnalisées
L'activité principale n'a qu'un bouton qui diffuse une intention lorsque vous cliquez dessus. Je ne suis pas sûr si c'est un problème de nommer l'action. Toute aide serait appréciée.
MainActivity:
package com.example.tsupt.bcr;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void broadcastIntent(View view){
Intent intent = new Intent();
intent.setAction("com.example.tsupt.bcr.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
Le récepteur de diffusion:
public class BR extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"It worked",Toast.LENGTH_LONG).show();
System.out.println("It worked");
}}
Le manifeste:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tsupt.bcr">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<receiver android:name="com.example.tsupt.bcr.BR">
<intent-filter>
<action android:name="com.example.tsupt.bcr.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</activity>
</application>
</manifest>
Le bouton à partir du fichier de mise en page:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="broadcastIntent"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="180dp"
app:layout_constraintTop_toBottomOf="@+id/textView"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent" />
Merci beaucoup d'avoir répondu, mais malheureusement cela n'a pas fonctionné aussi bien. –
Lors de l'exécution de l'application, je reçois ceci dans le moniteur Android: com.example.tsupt.bcr I/SendBroadcastPermission: action: com.example.tsupt.bcr.CUSTOM_INTENT, mPermissionType: 0 Est-ce que cela signifie que quelque chose ne va pas? –
Cette réponse a-t-elle finalement fonctionné? – fiddler