I tried to learn LocalBroadcastManager. Searched in web and implemented a simple app with Two activity to perform LocalBroadcastManager. But it's not working. I can't found what's wrong with my code. please help me!
here is my code.
FirstActivity.java
public class FirstActivity extends Activity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
Intent intent = new Intent("localReceiver");
LocalBroadcastManager.getInstance(FirstActivity.this).sendBroadcast(intent);
}
});
} }
SecondActivity.java
public class SecondActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textView = (TextView) findViewById(R.id.hi_text);
LocalBroadcastManager.getInstance(this).registerReceiver(message, new IntentFilter("localReceiver"));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(message);
}
private BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("SecondActivity", "Receiver Initiated...");
textView.setText("Intent receiver activated");
}
}; }
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:windowSoftInputMode="adjustResize|stateHidden"
android:label="SecondActivity" />
</application>
you are broadcasting something from FirstActivity, and you expect that SecondActivity receives it. In order this to happen you should be able to run two different Activitys at the same time, which is, by design, not possible. By the time you broadcast the string, you don't have anybody listening for it. Try using a Service to broadcast the String, with the receiving Activity resumed, and it will work
SecondActivity would looks like this:
private BroadcastReceiver uiUpdateReceiver;
onStart():
#Override
protected void onStart() {
LocalBroadcastManager.getInstance(SecondActivity.this).registerReceiver((uiUpdateReceiver), new IntentFilter("Your_Data");
super.onStart();
}
onCreate():
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
uiUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
onStop():
#Override
protected void onStop() {
LocalBroadcastManager.getInstance(ChatActivity.this).unregisterReceiver(uiUpdateReceiver);
super.onStop();
}
Hope it will help you.
Related
There are two applications : Caller, Callee
Case 1 >
When I launch Callee application from home screen, I can get an action("android.intent.action.MAIN") from INTENT.
While Callee is running, I launch Callee application with an action("andoird.intent.action.test") again from Caller application. Then I get the action("android.intent.action.MAIN"). not action("andoird.intent.action.test").
How can I get the action("andoird.intent.action.test")?
Case 2 >
When I launch Callee application with an action("andoird.intent.action.test"), I get the action("andoird.intent.action.test").
While Callee is running, I launch Callee application from the home screen. Then I get the action("andoird.intent.action.test"). not action("android.intent.action.Main").
How can I get the action("android.intent.action.Main")?
What am I missing to get the proper action?
Here is Caller code below.
public class CallerActivity extends AppCompatActivity {
public static final String ACTION_TEST = "android.intent.action.test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button test = (Button) findViewById(R.id.gotoSetting);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getPackageManager().getLaunchIntentForPackage(PACKAGE);
intent.setAction(ACTION_TEST);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
});
}
}
Here is Callee code below.
public class CalleeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("test", "onCreate()");
Log.e("test", getIntent().getAction());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e("test", "onNewIntent()");
Log.e("test", getIntent().getAction());
}
}
Here is Callee's AndroidManifest.
<activity
android:name=".CalleeActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.test"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Please help.
Replace this code:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e("test", "onNewIntent()");
Log.e("test", getIntent().getAction());// getIntent() will return old intent
}
with
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e("test", "onNewIntent()");
Log.e("test", intent.getAction()); //use new intent
}
i am new on android .
I am trying register the BroadcastReceiver in code at my activity. this is my code:
MyReciever class:
public class MyReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("===>", "onReceive: "+ intent.getAction());
Toast.makeText(context, "I got it "+ intent.getIntExtra("MyValue",0), Toast.LENGTH_SHORT).show();
}
}
myActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReciever = new MyReciever();
intentFilter = new IntentFilter();
intentFilter.addAction("test");
}
#Override
protected void onResume() {
registerReceiver(myReciever, intentFilter);
super.onResume();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.safarayaneh.mybroadcastreciever">
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
when i run my app, nothing happen and toast not comes up! I've read this and this article and i don't understand that where is my problem.
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this line makes the broadcastreceiver
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I got it "+ intent.getIntExtra("MyValue",0), Toast.LENGTH_SHORT).show();
}
};
//this line register broadcastreceiver
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mBroadcastReceiver, new IntentFilter("test"));
//this line calls the broadcastreceiver
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("test"));
}
}
Register your broadCast receiver in OnResume and unregister it in OnPause like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReciever = new MyReciever();
intentFilter = new IntentFilter();
intentFilter.addAction("test");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(reMyreceive);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(reMyreceive, filter);
}
I have 2 Activity one is sending a broadcust and another receiving. But receiver never get called -
MainActivity
public class MainActivity extends AppCompatActivity {
public static String BROADCAST_ACTION = "com.aj.SHOWTOAST";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendBroadcast(View v) {
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
this.sendBroadcast(broadcast);
}
}
ToastDisplay
public class ToastDisplay extends AppCompatActivity {
public static String BROADCAST_ACTION = "com.aj.SHOWTOAST";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toast_display);
IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
this.registerReceiver(new Receiver(), filter);
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.d("TAG", "onReceive: SMS SENT!!");
Toast.makeText(getApplicationContext(), "SMS SENT!!", Toast.LENGTH_SHORT).show();
}
}
}
Manifest
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ToastDisplay">
<intent-filter>
<action android:name="com.aj.SHOWTOAST" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
You can put broad cast receiver in your by this way also.
public class SampleActivity extends AppCompatActivity {
public static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE";
// Receive Message through Broadcast Receiver...
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String receiver = intent.getStringExtra("receiver");
Toast.makeText(context, "" + receiver, Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mobile_verify);
}
#Override
protected void onResume() {
super.onResume();
//registering the receiver...
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
}
#Override
protected void onPause() {
super.onPause();
//Unregistering the receiver...
unregisterReceiver(mHandleMessageReceiver);
}
}
Broadcast receiver can be called through the following intent. You can use this intent any where to call this broadcast receiver. For example there are two activity and in those two activities you are using this receiver and you calling this intent from some other class which handles server response or database result. Whichever activity is in front that activities receiver will be called.i.e., activity one is in front if you are calling this receiver intent means then receiver in the activity one will be triggered.
Intent intent = new Intent(SampleActivity.DISPLAY_MESSAGE_ACTION);
intent.putExtra("receiver", "testMessage");
sendBroadcast(intent);
If the broadcast is going to happen within the app then it is good to use LocalBroadCastManager
public class MainActivity extends AppCompatActivity {
public static String BROADCAST_ACTION = "com.aj.SHOWTOAST";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendBroadcast(View v) {
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(broadcast);
}
}
public class ToastDisplay extends AppCompatActivity {
public static String BROADCAST_ACTION = "com.aj.SHOWTOAST";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toast_display);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//your code here
}
};
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter(BROADCAST_ACTION)); }
}
You cant send boradcast one activity to another activity. So you have to do it like below.
First implement the Receiver as a separate class.
Receiver.java:
public class Receiver extends BroadcastReceiver {
public Receiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Hello", Toast.LENGTH_LONG).show();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String BROADCAST_ACTION = "com.aj.SHOWTOAST";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendBroadcast(View v) {
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
this.sendBroadcast(broadcast);
}
}
And manifest should be as below.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".Receiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.aj.SHOWTOAST"/>
</intent-filter>
</receiver>
I am building a simple android application and it has two Activities and a IntentService. My IntentService plays music over every activity(thats what I want) but if I leave the app the music still plays (example: if I press the home button it will take me to the desktop, putting my activity in the onpause state but the music from that app is still playing). Any help would be appreciated....
code below
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent= new Intent(this, BackgroundMusic.class);
startService(serviceIntent);
}
public void ShipPick(View view){
Intent activityIntent= new Intent(this, ShipChoiceActivity.class);
startActivity(activityIntent);
}
}
Background Music Service
public class BackgroundMusic extends IntentService {
MediaPlayer mp;
public BackgroundMusic() {
super("BackgroundMusic");
}
Handler HN = new Handler();
private class PlayMusic implements Runnable {
public void PLayMusic(){
}
public void run(){
mp = MediaPlayer.create(getApplicationContext(), R.raw.musicfile);
mp.start();
}
}
#Override
protected void onHandleIntent(Intent intent) {
HN.post(new PlayMusic());
}
public void onPause() {
mp.pause();
}
public void onResume() {
mp.start();
}
protected void onStop() {
mp.stop();
mp = null;
}
}
second activity
public class ShipChoiceActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ship_choice);
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.starwars"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name=".BackgroundMusic" />
<activity
android:name="com.example.ship.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>
<activity android:label="#string/app_name" android:name="ShipChoiceActivity"/>
</application>
</manifest>
For controlling BackgroundMusic Service from Activity you will need to use custom BroadcastReceiver to communicate with service when application is going in onpause state.
Register BroadcastReceiver In BackgroundMusic :
public class MusicServiceBroadCast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
if(<Match for action>){
if Action is for pause then call pause for MediaPlayer
}else{
if Action for Play ...
}
}
}
#Override
protected void onHandleIntent(Intent intent) {
//... Register BroadcastReceiver
registerReceiver(new MusicServiceBroadCast(), new IntentFilter(
"com.xx.PAUSE_MUSIC_ACTION"));
HN.post(new PlayMusic());
}
Send BroadcastReceiver from Activity onPause :
Intent intent = new Intent();
intent.setAction("com.xx.PAUSE_MUSIC_ACTION");
sendBroadcast(intent);
my receiver is not firing, code below:
AndroidManifest
<recevier android:name=".NoticeReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.clublifestyle.NoticeService.BROADCAST" />
</intent-filter>
</recevier>
NoticeReceiver.java
public class NoticeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "ASDASD", Toast.LENGTH_SHORT).show();
}
}
CLMainActivity.java
public class CLMainActivity extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.createTabs();
Intent i2 = new Intent(this, NoticeReceiver.class);
this.sendBroadcast(i2);
}
}
Can you help me to find out why?
Thanks!
Try to also set the action for the Intent i2:
Intent i2 = new Intent();
i2.setAction("com.clublifestyle.NoticeService.BROADCAST");
this.sendBroadcast(i2);
EDIT
There is a typo in your manifest. You have the <receiver> tag written as <recevier>. Your app sees no <receiver>