Search code examples
androidandroid-intentbroadcastreceiverreceiver

How can I start receiver class from an Activity in android?


I have an activtiy and a receiver.class with broadcastreceiver. I would like to start receiver from mainactivity but I could not do this with my solution.

Here is may way

Intent iinent= new Intent(MainActivity.this,MyReceiver.class);
        startActivity(iinent);

When I try this app says me Unfortunately app has stopped'' and my logcat says this intent' line s incorrect.

Is there another way to do this?


Solution

  • For Sending Broadcast Receiver Broadcast Receiver must be registered

    in Manifest

    <receiver android:name="TestReceiver">
            <intent-filter>
                <action android:name="ACTION_NAME"/>
            </intent-filter>
        </receiver>
    

    In Activity

      IntentFilter filter = new IntentFilter();
          filter.addAction("ACTION_NAME");
    
       BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          //do something based on the intent's action
        }
      }
         registerReceiver(receiver, filter);
    
    
    
    SendBroadcast
    
    
     Intent intnet = new Intent("ACTION_NAME");
        sendBroadcast(intnet);