我正在尝试从bc_from广播到bc_to 如果我在Activity bc_to中使用它可以正常工作:
registerReceiver(receiver, filter);
如果我在Manifest中定义接收器,它就不起作用
我从文件中了解到,自26年以来这可能是不可能的
所以我正在寻找能够达到活动bc_to的任何解决方案,即使它没有运行。
// package com.yotam17.ori.bc_from;
public class MainActivity extends AppCompatActivity {
private static final String BC_ACTION = "com.yotam17.ori.bc.Broadcast";
private void send() {
Intent intent = new Intent(BC_ACTION);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send();
}
}
bc_from的代码包含Manifest和两个clases:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name="com.yotam17.ori.bc_to.MyReceiver" >
<intent-filter>
<action android:name="com.yotam17.ori.bc.Broadcast"/>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
// package com.yotam17.ori.bc_to;
public class MainActivity extends AppCompatActivity {
private static final String BC_ACTION = "com.yotam17.ori.bc.Broadcast";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Register MyReceiver
IntentFilter filter = new IntentFilter(BC_ACTION);
MyReceiver receiver = new MyReceiver();
registerReceiver(receiver, filter); //<<<<<< Does not work w/o this
}
}
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Got it!!!" , Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
谢谢!
setComponent()解决了它
我以前从未使用过setComponent(),但是找到了一个详细的例子here。
为了使它成为一个工作示例 - 这里是修改后的send()代码:
private void send() {
Intent intent = new Intent(BC_ACTION);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setComponent(new ComponentName("com.yotam17.ori.bc_to","com.yotam17.ori.bc_to.MyReceiver"));
sendBroadcast(intent);
}