簡體   English   中英

BroadcastReceiver未接收

[英]BroadcastReceiver not receiving

我已經閱讀了SO問題中的說明和示例,但是仍然無法實現一個簡單的BroadcastReceiver,它根本什么都沒收到,有人可以就以下代碼提供一些建議嗎?

n

我的活動:

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>

您確定您的服務正在開始嗎? 看起來您只是創建一個空白的意圖並調用startService()。

您的broadcastReceiver似乎是正確的。

您需要在AndroidManifest.xml中注冊接收器 除非您這樣做,否則Android操作系統將無法找到您的BroadcastReceiver。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM