我知道当我在意图过滤器的清单中定义一个广播接收器时,我可以定义类别,它是可选的。
D:\aaa111\child
我用谷歌搜索,但无法得到它添加类别或我如何使用它的确切点。我很感谢给我一些例子。
答案 0 :(得分:-3)
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* send
*
*/
public class MainActivity extends Activity {
private static final String MY_ACTION = "com.chaowen.action.MY_ACTION";
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.Button01);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent= new Intent();
intent.setAction(MY_ACTION);
//Intent message
intent.putExtra("msg", "ha ha");
//send
sendBroadcast(intent);
}
});
}
}
MyReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* receive
*
*/
public class MyReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//get Intent message
String msg = intent.getStringExtra("msg");
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:text="send..."
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
的AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chaowen"
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=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="MyReceive"
>
<intent-filter>
<action
android:name="com.chaowen.action.MY_ACTION" />
</intent-filter>
</receiver>
</application>