Blog purpose for android basic example for android app developer. any query please my contact

Friday, 17 February 2023

Android Local Brodcast manager example

 Android Local Brodcast manager example

The Local Broadcast Manager was introduced to the Android Support Library to simplify the process of registering for, and sending, Broadcast Intents between components within your application.

Because of the reduced broadcast scope, using the Local Broadcast Manager is more efficient than sending a global broadcast. It also ensures that the Intent you broadcast cannot be received by any components outside your application, ensuring that there is no risk of leaking private or sensitive data, such as location information.



what is local brodcast in android:

In Android, a local broadcast is a way for an app to send and receive messages within the same app. Unlike system-wide broadcasts that are sent to all apps on the device, local broadcasts are only visible within the app that sends them.


Local broadcasts can be useful for several reasons. For example, an app might use a local broadcast to notify other components within the app that a certain event has occurred. This can be more efficient than using system-wide broadcasts, as local broadcasts don't need to be processed by other apps on the device.




Example Android local brodcast :


import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.support.v4.content.LocalBroadcastManager;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

 

public class MainActivity extends Activity implements OnClickListener {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button b1 = (Button) findViewById(R.id.button1);

        b1.setOnClickListener(this);

    }

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }

 

    @Override

    public void onClick(View v) {

        // TODO Auto-generated method stub

        sendBroadcast();

        startActivity(new Intent("android.intent.action.Activityone"));

 

    }

 

    public void sendBroadcast() {

        Intent intent = new Intent("send");

        intent.putExtra("current speed", "102.4");

        intent.putExtra("latitude", "12.2342342");

        intent.putExtra("longitude", "12.21124");

        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    }

}

No comments:

Post a Comment