微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从Android中的活动开始播放收信人

我想从活动中开始一个广播接收者.我有一个Second. java文件,它扩展了一个广播接收器和一个Main.java文件,我必须从中启动广播接收器.
我也尝试在Main.java中做的一切,如下,但不知道如何在清单文件中定义…

Main.java:

public class Main extends Activity {
/** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
String rec_data = "nothing Received";
private broadcastReceiver myReceiver = new broadcastReceiver() {

        public void onReceive(Context context,Intent intent) {
            // Todo Auto-generated method stub
            if( intent.getStringExtra("send_data")!=null)
                    rec_data = intent.getStringExtra("send_data");
            Log.d("Received Msg : ",rec_data);
        }
    }; 
    }
    protected void onResume() {
        IntentFilter intentFilter = new IntentFilter();
        //intentFilter.addDataType(String);
        registerReceiver(myReceiver,intentFilter);
        super.onResume();
    }

  @Override
protected void onPause() {
// Todo Auto-generated method stub
    super.onPause();
    this.unregisterReceiver(this.myReceiver);
}

}

如果我不能像上面那样在一个类中做任何事情,那我该如何从Main.java调用broadcast Receiver?有谁能让我知道我在做错了什么?谢谢!

解决方法

使用这个为什么要发送自定义广播:

定义动作名称

public static final String broADCAST = "PACKAGE_NAME.android.action.broadcast";

AndroidManifest.xml注册接收器:

<receiver android:name=".myReceiver" >  
    <intent-filter >  
        <action android:name="PACKAGE_NAME.android.action.broadcast"/>  
    </intent-filter>  
</receiver>

注册会员:

IntentFilter intentFilter = new IntentFilter(broADCAST);
registerReceiver( myReceiver,intentFilter);

从您的活动发送广播:

Intent intent = new Intent(broADCAST);  
        Bundle extras = new Bundle();  
        extras.putString("send_data","test");  
        intent.putExtras(extras);  
        sendbroadcast(intent);

你的broadcastReceiver:

private broadcastReceiver myReceiver = new broadcastReceiver() {

        public void onReceive(Context context,Intent intent) {
            // Todo Auto-generated method stub
             Bundle extras = intent.getExtras();
           if (extras != null){  
           {
                    rec_data = extras.getString("send_data");
            Log.d("Received Msg : ",rec_data);
            }
        }
    };

有关Custom broadcast的更多信息,请参阅Custom Intents and Broadcasting with Receivers

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐