我已经阅读了SO问题中的说明和示例,但仍然无法实现简单的BroadcastReceiver,它根本没有收到任何东西,有人可以就以下代码提供一些建议吗?
TNX
我的活动:
public class Receiver1Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(MyService.MY_ACTION);
registerReceiver(new MyReceiver(), filter);
Intent intent = new Intent();
startService(intent);
}
}
我的接收者:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
Log.i("MyReceiver", "onreceive");
}
}
我的服务,发送广播:
public class MyService extends Service {
public static final String MY_ACTION = "com.receiver1.myaction";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent intent2 = new Intent(MY_ACTION);
sendBroadcast(intent2);
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
我的清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.receiver1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".Receiver1Activity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"></service>
</application>
</manifest>
答案 0 :(得分:1)
您确定自己的服务即将开始吗?看起来你只是创建一个空白的意图并调用startService()。
您的broadcastReceiver似乎是正确的。
答案 1 :(得分:0)
您需要register your receiver in your AndroidManifest.xml。在您这样做之前,Android操作系统将无法找到您的BroadcastReceiver。