簡體   English   中英

Android廣播接收器不工作

[英]Android broadcast receiver not working

我試圖讓廣播接收器工作。 應該盡可能簡單,我有這樣的清單:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytest.intentRec" android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:debuggable="true">
        <activity android:name=".mainAct" 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="com.mytest.intentRec.MyIntentRec"
                  android:enabled="true" >
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion="7" />
</manifest> 

正如您所看到的,我有一個主要活動mainAct,這只會在啟動后發送廣播:

public class mainAct extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.sendBroadcast(new Intent());
    }
}

我有一個MyIntentRec類,它盡可能簡單:

public class MyIntentRec extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v("IntentRec", "got it");
    }
}

我期望的是,當我啟動我的應用程序時,廣播被發送並被拾取並且寫入了日志條目。 我沒有看到日志條目,我沒有看到任何錯誤。 我懷疑在清單中發送錯誤或發送廣播。 我剛剛在那里創建了一個空的意圖,是否需要對某些屬性有一些意圖?

請為你的Intent setClass

EX:

public class mainAct extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i=new Intent("any string");
        i.setClass(this, MyIntentRec.class);
        this.sendBroadcast(i);
    }
}

這就是它的含義“沒有任何過濾器意味着它只能由指定其確切類名的Intent對象調用。”

[老答案]
您應該在清單中注冊所需的操作類型。
例如:

    <receiver android:name="com.mytest.intentRec.MyIntentRec" android:enabled="true" >
        <intent-filter>
            <action  android:name="your.intent" />
        </intent-filter>
    </receiver>

發送,

this.sendBroadcast(new Intent("your.intent"));

只做new Intent();是不夠的new Intent(); 你必須用一些動作來指定它。 此外,您必須在清單中指定此特定操作的intent過濾器。 在這里這里閱讀更多內容。

您沒有在BroadcastReceiver的清單中定義任何Intent Filters。 為自定義操作類型指定一個。 您還必須在啟動時的Brodcast中定義此自定義Action類型。

嘗試指定接收方應在清單中捕獲的操作。 你可以這樣做:

<receiver android:name="com.mytest.intentRec.MyIntentRec">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

暫無
暫無

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

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