我正在尝试从bc_from广播到bc_to。 如果我在Activity bc_to中使用它可以正常工作:
registerReceiver(receiver, filter);
如果我在Manifest中定义接收器,它就不起作用。 我从文档中了解到,自26年以来这可能是不可能的。 所以我正在寻找任何能够达到Activity 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();
}
}
以及来自容器Manifest和两个类的bc的代码:
<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();
}
}
谢谢! 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);
}