我正在尝试制作broadcast receiver
,当用户点击我的其他应用活动中的toast
时会显示button
消息。
但是receiver
没有显示结果。
我的代码在
下面我的接收器应用
MyReceiver :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast has been received!", Toast.LENGTH_LONG).show();
}
}
清单:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xyz.receivebroadcast">
<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.xyz.broadcasts"></action>
</intent-filter>
</receiver>
</application>
我的发件人应用
我发送广播的MainActivity
就在这里。
MainActivity :
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SendOutBroadcast(View view){
Intent i = new Intent();
i.setAction("com.example.xyz.broadcasts");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
}
}
activity_main.xml中:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xyz.broadcasts.MainActivity">
<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="SendOutBroadcast"
android:text="Send Broadcast"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:1)
在您的情况下,activity
Intent
应该是这样的:
Intent intent = new Intent();
intent.setAction("com.example.xyz.broadcasts");
intent.putExtra("KeyName","code1id");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setComponent(
new ComponentName("com.pkg.AppB","com.pkg.AppB.MainActivity"));
sendBroadcast(intent);
尝试此操作可能有助于您或visit获取更多信息。
注意 - 这可能不适用于 Android O ,因为在Android O中 implicit broadcast
是禁止的<强> Here 即可。 (还要归功于你@Muhammad Arslan Maqsood)
答案 1 :(得分:0)
我发现了问题:问题不在于代码,实际上Android O禁用了“Implicit broasdcast”功能。见this