Android服务中的广播接收器:问题

3
我目前正在尝试在Android中创建一个具有与服务内已启动的BroadcastReceiver通信功能的Activity,但我无法很好地完成它。我不知道问题可能是什么,因为(我认为)我已经遵循了所有必要的步骤。
此外,我有其他可以与这个BroadcastReceiver进行通信的Activity,没有任何问题。我用于出现问题的代码如下:
在文件ActivityList.java(另一个Activity)中注册操作名称:
public static final String ACTION1 = "com.test.ActionOne";
public static final String ACTION2 = "com.test.ActionTwo";

在扩展了Service的文件GestTree.java中,使用IntentFilter注册操作:

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);

在扩展了 BroadcastReceiverGestTree.java 中的 private class ReceptoronReceive() 函数内:

public final void onReceive(final Context context, final Intent intent) {
    String action = intent.getAction();
    if (action.equals(ActivityList.ACTION1)) {
    Log.d(tag, "Test Passed!");
    }
}

AndroidManifest.xml中,State3Activity(我想要与服务进行通信的活动)的服务和活动定义如下:

<activity
    android:name="State3Activity"
    android:label="@string/app_name" >    
</activity>

<service
     android:name="GestTree"
     android:enabled="true"
     android:label="@string/app_name" >
</service>

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);

                }
            });
}

问题就在这里。当我按下按钮时,意图从未进入该类的onReceive()函数。我漏掉了什么?


好的,我还是比较新手,抱歉。@DamianKozlak - Alberto
你为什么要使用“BroadcastReceiver”呢?为什么不直接与你的“Service”通信? - pskink
你是将广播监听器定义在 Activity 类的内部还是单独作为一个 Java 文件? - insomniac
1
可能是上下文出了问题,我不知道。你尝试过在AndroidManifest.xml文件中使用意图过滤器声明吗? - insomniac
它解决了你的问题吗? - Parag Kadam
显示剩余23条评论
1个回答

2

您确定您的服务已经启动了吗?如果您没有启动服务,onCreate()方法将不会被执行,接收器也将无法注册。


好的,没错,就是这样Lauren!我必须在不同的地方启动服务,那里我做了sendBroadcast!非常感谢。 - Alberto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接