Android BroadcastReceiver无法接收广播

时间:2014-06-30 03:14:36

标签: android

      //HERE ARE THE CODE

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    private class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "received message in     activity..!", Toast.LENGTH_SHORT).show();
            Button b=(Button)findViewById(R.id.button);
            b.setText("received");
        }
    };

    private static final String ACTION_STRING_ACTIVITY = "ToActivity";
    private Receiver activityReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activityReceiver=new Receiver();

        if (activityReceiver != null) {
            IntentFilter intentFilter = new     IntentFilter(ACTION_STRING_ACTIVITY);
            intentFilter.addDataScheme("file");
            registerReceiver(activityReceiver, intentFilter);
        }



        findViewById(R.id.button).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Button b=(Button)findViewById(R.id.button);
                sendBroadcast();
                Log.d("SampleActivity", "broadcast sent");
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("Service", "onDestroy");
        unregisterReceiver(activityReceiver);
    }

    private void sendBroadcast() {

        Intent new_intent = new Intent();
        new_intent.setAction(ACTION_STRING_ACTIVITY);
        new_intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        sendBroadcast(new_intent);
        Button b=(Button)findViewById(R.id.button);
    }
}

我正在测试Android BroadcastReceiver,但我正在研究这一整天 但仍然无法使其发挥作用。当我点击时,我在MainActivity中定义了一个接收器 按钮,它应该接收广播并将按钮上的文本设置为 "接收"

1 个答案:

答案 0 :(得分:0)

确保您的Manifest中包含以下内容:

 <receiver
        android:name="com.<your_package>.MainActivity.Receiver"
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.<your_package>.ToActivity" />
        </intent-filter>
 </receiver>

好的,我明白了。我删除了&#34; intentFilter.addDataScheme(&#34;文件&#34;);&#34;然后它工作了 但是,我没有在清单代码中注册接收器。

非常感谢你