【发布时间】:2022-02-14 20:25:24
【问题描述】:
所以我制作了两个不同的应用程序,一个发送广播,另一个接收广播并显示敬酒。但是,当我关闭接收器应用程序时,即使我在清单文件中定义了接收器,第二个应用程序也不再接收广播。
app1的MainActivity中的广播发送者。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction("com.example.ali.rrr");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
Log.e("Broadcast","sent");
}
});
}
App 2 广播接收器:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Broadcast has been recieved!", Toast.LENGTH_SHORT).show();
Log.e("SUCCESS", "IN RECIEVER");
//throw new UnsupportedOperationException("Not yet implemented");
}
App 2s 清单:
<?xml version="1.0" encoding="utf-8"?>
<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=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.ali.rrr" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".Main2Activity"
android:label="@string/title_activity_main2"
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>
【问题讨论】:
-
当你的应用被销毁时,你应该取消注册你的广播接收器,你可以使用服务而不是广播接收器。
-
它在打开应用 2(接收器应用)时工作?
-
@MohitKacha 我试图让它作为广播接收器工作,即使应用程序关闭,清单中静态注册的接收器也应该工作。
-
@JdPrajapati 是的,当我在后台保持 App2 打开时它正在工作。
-
@kumail 你只能使用服务和接收者的组合来实现这一点。但是您的代码使用 Activity 进行广播,因此这是不可能的,因为 Activity 需要上下文,而 Activity 在后台时无法提供上下文
标签: java android android-intent broadcastreceiver