无法从活动向其他人发送广播:android

时间:2012-04-24 10:01:41

标签: android

我有从一个活动向其他活动发送广播接收的问题..没有工作我的代码在下面..请参考它..

发送课程是:

    public class SendBroadcast extends Activity {
public static String BROADCAST_ACTION = "com.unitedcoders.android.broadcasttest.SHOWTOAST";

/** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        sendBroadcast();
        }

    });
}




  public void sendBroadcast(){

    Intent broadcast = new Intent();
    broadcast.setAction("com.unitedcoders.android.broadcasttest.SHOWTOAST");
    sendBroadcast(broadcast);
}

}

和复习课程是:

  public class ToastDisplay extends Activity {

private BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("asdasd","sdasdasd");
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "%%%%%%%%%%%%received", Toast.LENGTH_SHORT).show();

    }
};

@Override
protected void onResume() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(SendBroadcast.BROADCAST_ACTION);
    registerReceiver(receiver, filter);

    super.onResume();
}

@Override
protected void onPause() {
    unregisterReceiver(receiver);
    super.onPause();
}

}

清单文件是::::

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.unitedcoders.android.broadcasttest"
  android:versionCode="1"
  android:versionName="1.0">
 <uses-sdk android:minSdkVersion="4" />

  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".SendBroadcast"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  <activity android:name=".ToastDisplay">

    <intent-filter>
        <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST">  </action>
    </intent-filter>
  </activity>

  </application>
  </manifest>

2 个答案:

答案 0 :(得分:1)

您尚未在Manifest中注册您的Receiver:已注册为

<receiver android:name="receiver">
<intent-filter>
<action
android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
</intent-filter>
</receiver>

答案 1 :(得分:-1)

如果要将数据从一个活动广播到另一个活动,只需使用Intent即可。在第二个活动的onDestroy方法中,从您要发送数据的位置,创建意图对象和广播数据作为额外意图,然后使用intent.getExtra()方法onReceive()方法broadcastReceiver 1}} class。

了解更多详情: follow this tutorial