BroadCast接收器触发

时间:2012-08-19 17:01:42

标签: android broadcastreceiver

我想简单地从我的AlarmManager Activity中调用BroadClass Activity中定义的一个函数。为此我已经制作了一个广播接收器,我从Alarmmanager Activity触发它,但我没有得到回应

AlarmManager活动(从这里开始广播)

 package com.mainActivity;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;

    public class AlarmManagerActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Intent intent = new Intent(AlarmManagerActivity.this,BroadClass.class);
            intent.setAction("BROADCAST_ACTION");
            sendBroadcast(intent);
    }
    }

我已定义广播接收器的BroadClass活动

   package com.mainActivity;


    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.widget.Toast;



    public class BroadClass extends Activity {

        public BroadcastReceiver broadCast;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);



            registerReceiver(new BroadcastReceiver() {

                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    // TODO Auto-generated method stub

                    Toast.makeText(BroadClass.this, "SDK Manager Activity", Toast.LENGTH_SHORT).show();


myFunction();   //which i want to call

                }
            },new IntentFilter("BROADCAST_ACTION"));


        }


        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            IntentFilter filter = new IntentFilter();
            filter.addAction("BROADCAST_ACTION");
            registerReceiver(broadCast, filter);

            super.onResume();


        }

public void myFunction(){

//mycode here

    }

请帮帮我.. 提前致谢

2 个答案:

答案 0 :(得分:0)

更改

Intent intent = new Intent(AlarmManagerActivity.this,BroadClass.class);

Intent intent = new Intent();

还要确保在发送广播时注册接收器。 哦,不要忘记在离开活动时取消注册接收器。否则你会得到令人讨厌的例外。

答案 1 :(得分:0)

您是否尝试在onResume中删除BroadcastReceiver设置?您正在注册一个带有空IntentFilter的新广播接收器。

请记住,onResume总是在onCreate之后运行,并且在您的情况下重置最初设置的过滤器。