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

前端之家收集整理的这篇文章主要介绍了从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

原文链接:https://www.f2er.com/android/311218.html

猜你在找的Android相关文章