Reputation: 396
I am currently trying to create an Activity in Android with the capabilities of communicating with a started BroadcastReceiver
inside of a service but I can't manage to do it well. I don't really know what the problem could be since (I think) I have followed all necessary steps.
In addition, I have other Activities which can communicate with this BroadcastReceiver
without any problems. The code that I am using for the one I am having problems with is the following:
Registration of the name of the action in file ActivityList.java
(Another activity):
public static final String ACTION1 = "com.test.ActionOne";
public static final String ACTION2 = "com.test.ActionTwo";
Registration of the actions with IntentFilter
in the file GestTree.java
which extends a Service
:
Inside onCreate()
:
IntentFilter filter;
filter = new IntentFilter();
filter.addAction(ActivityList.ACTION1);
filter.addAction(ActivityList.ACTION2);
rec = new Receptor(); // This is a class which extends BroadcastReceiver
registerReceiver(receptor, filter);
Inside the function onReceive()
of the private class Receptor
of GestTree.java
which extends BroadcastReceiver
:
public final void onReceive(final Context context, final Intent intent) {
String action = intent.getAction();
if (action.equals(ActivityList.ACTION1)) {
Log.d(tag, "Test Passed!");
}
}
The definition of the service and the Activity State3Activity
(the one I want to communicate with the service) in AndroidManifest.xml
:
<activity
android:name="State3Activity"
android:label="@string/app_name" >
</activity>
<service
android:name="GestTree"
android:enabled="true"
android:label="@string/app_name" >
</service>
Code inside State3Activity.java
:
public class State3Activity extends Activity {
Button mButton;
EditText editText_Name;
EditText editText_Desc;
private final String tag = this.getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.state3_layout);
mButton = (Button)findViewById(R.id.button_myButton);
editText_Nombre = (EditText)findViewById(R.id.editText_Name);
editText_Descripcion = (EditText)findViewById(R.id.editText_Desc);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent;
intent = new Intent();
intent.setAction(ActivityList.ACTION1);
// I have tried with all this combination of lines
// but none of them works
//intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
//intent.setClass(State3Activity.this, GestTree.class);
//intent.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(intent);
}
});
}
There is where the problem comes. The intent never enters on the onReceive()
function of the class when I press the button. What am I leaving?
Upvotes: 3
Views: 460
Reputation: 86
Are you sure your service started? If you have not start the service, the method of onCreate()
will not be executed, and the receiver will not be registed.
Upvotes: 2