简体   繁体   中英

Broadcastreceiver not receiving?

I am trying to pass values from service to activity using broadcast

I am using following code to call broadcast in service

            Intent i = new Intent();
            i.putExtra("test",result);
            sendBroadcast(i);

And receiving in main activity using following code

     public class myreciver extends BroadcastReceiver{
            public String data =null;
            @Override
        public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                String datapassed = intent.getStringExtra("test");

         }
 }

In Main Activity

             myreciver m = new myreciver();
             IntentFilter intentFilter = new IntentFilter();
             intentFilter.addAction(MyService.MY_ACTION);
             registerReceiver(m, intentFilter);

but my receiver is not called.

Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pragadees.restex" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MainActivity$myreciver" >
        </receiver>

        <service
            android:name=".MyIntentService"
            android:exported="false" >
        </service>
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="false" >
        </service>

        <activity
            android:name=".display"
            android:label="@string/title_activity_display" >
        </activity>
    </application>

</manifest>

Action missing in Intent which is passing to sendBroadcast method.do it as:

Intent i = new Intent(MyService.MY_ACTION); //<< pass Action to Intent
i.putExtra("test",result); 
sendBroadcast(i);

use broad cast like this

 Intent i = new Intent("Broadcastname");

            context.sendBroadcast(i);

and now receive broad cast like this way

@Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        IntentFilter intentFilter = new IntentFilter("Broadcastname");
    BroadcastReceiver   Receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        // to your work here 

                    }
                });

            }
        };

    this.registerReceiver(Receiver, intentFilter);

finally unregister in onstop() method

@Override
    protected void onStop() {
        // TODO Auto-generated method stub

        if (Receiver != null) {
            this.unregisterReceiver(this.Receiver);
        }
        super.onStop();
    }

Android's BroadcastReceiver is part of a framework that allows activities and services to send data to one another, even if they belong to separate apps. This is how apps share data with one another, such as when you share a picture from your gallery to Facebook or G+. However, this extensive capability means that you have to be careful about how you filter your requests, which means that it can be harder to just send a quick message from inside your own app.

If you don't need to worry about receiving data from other apps, then you can use the LocalBroadcastManager , which is an implementation of BroadcastReceiver that is confined inside of your own app's jurisdiction. It can't send or receive intents from outside your app. Its interface is nearly identical to BroadcastReceiver 's:

public class MyActivity extends Activity {

  private LocalBroadcastManager mBroadcastManager;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mBroadcastManager = LocalBroadcastManager.getInstance(this);

    //Build an intent filter so you only receive relevant intents
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("Test from Service to Activity");

    //Register a new BroadcastReceiver with the LocalBroadcastManager
    mBroadcastManager.registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        String dataPassed = intent.getStringExtra("test");

      }                               
    }, intentFilter);

    //If you ever want to send a broadcast, use this:
    Intent sendIntent = new Intent(this, MyService.class);
    sendIntent.setAction("Test from Activity to Service");
    sendIntent.putExtra("test", "This is a test from Activity!");
    mBroadcastManager.sendBroadcast(sendIntent);
  }
}

//Then in your Service...

public class MyService extends Service {

  private LocalBroadcastManager mBroadcastManager;

  public void onCreate() {
    mBroadcastManager = LocalBroadcastManger.getInstance(this);
  }

  public int onStartCommand(Intent intent, int flags, int startId) {

    //Build intent filter
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("Test from Activity to Service");

    mBroadcastManger.registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        String dataPassed = intent.getStringExtra("test");

      }

    }, intentFilter);

    //To send data to the activity:
    Intent sendIntent = new Intent(this, MyActivity.class);
    sendIntent.setAction("Test from Service to Activity");
    sendIntent.putExtra("test", "This is a test from Service!");
    mBroadcastManager.sendBroadcast(sendIntent);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM