gpt4 book ai didi

Android广播接收器不工作

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:59:07 25 4
gpt4 key购买 nike

我尝试让广播接收器工作。应该尽可能简单,我有这样的 list :

<?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>

如您所见,我有一个主要 Activity 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");
}
}

我期望的是,当我启动我的应用程序时,会发送和接收广播,并写入日志条目。我没有看到该日志条目,也没有看到任何错误。我怀疑 list 或发送广播有误。我刚刚在那里创建了一个空 Intent ,它是否需要具有某些属性的 Intent ?

最佳答案

请为您的 Intent setClass

例如:

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 对象调用。”

[旧答案]
您应该在 list 中注册您需要什么样的操作。
例如:

    <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"));

关于Android广播接收器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5473634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com