Broadcast receiver onReceive() never called

2019-01-18 15:47发布

问题:

I get this issue in ICS, but not in previous versions:

From App1, I am sending broadcast and trying to receive it in App 2 activity. But the onReceive is never called in App 2's activity.

I cannot understand what is that block's onReceive from getting called, though I have specified everything correctly.

I run the BroadcastReceive first and then BroadcastSend

Any help which would help me resolve this is much appreciated.

App1 send activity

public class BroadcastSend extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent i = new Intent();
    i.setAction("edu.ius.rwisman.custom.intent.action.TEST");
    i.putExtra("url","ww.ius.edu");
    sendBroadcast(i);
}

App 2 receive activity

public class BroadcastReceive extends BroadcastReceiver{
// Display an alert that we've received a message.    
@Override 
public void onReceive(Context context, Intent intent){
    System.out.println("Inside onReceive");
    String url = intent.getExtras().getString("url");
    Toast.makeText(context, "BroadcastReceive:"+url, Toast.LENGTH_SHORT).show();
  }

Manifest of App 2

<?xml version="1.0" encoding="utf-8"?>

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <receiver android:name="edu.ius.rwisman.BroadcastReceive.BroadcastReceive" android:enabled="true" android:exported="true"> 
        <intent-filter>
            <action android:name="edu.ius.rwisman.custom.intent.action.TEST"/>
        </intent-filter>
    </receiver>
</application>

回答1:

In ICS you won't receive broadcasts until your app is started manually at least once.in Android 3.1+, apps are in a stopped state if they have never been run, or have been force stopped. The system excludes these apps from broadcast intents. They can be included by using the Intent.FLAG_INCLUDE_STOPPED_PACKAGES flag like this..

i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);