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);
}
}
Related
I know that exists thread about that, but I can't get how to do it, I only need send data a Broadcast, this is the code
Main activity
public void passData(){
passIntent = new Intent(this,Notification_Reciever.class);
path=String.valueOf(recibidor_file.get(recibidor_position).getAbsolutePath());
passIntent.putExtra("KEY",path);
sendBroadcast(passIntent);
}
BroadCast
public class Notification_Reciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
String value=intent.getStringExtra("KEY");
if(Constantes.ACTION.PLAY_ACTION.equals(action)){
actionPlay();
Toast.makeText(context,""+value,Toast.LENGTH_SHORT).show();
}
if(Constantes.ACTION.PREV_ACTION.equals(action)){
}
if(Constantes.ACTION.NEXT_ACTION.equals(action)){
}
}
Manifest
<receiver android:name=".Notification_Reciever">
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="PLAY_ACTION"/>
</intent-filter>
</receiver>
Always get null
Since you have intent-filter defined in manifest,
<intent-filter>
<action android:name="PLAY_ACTION"/>
</intent-filter>
You need to set action to your intent in order to receive data...
passIntent = new Intent(this,Notification_Reciever.class);
passIntent.setAction("PLAY_ACTION");
path = String.valueOf(recibidor_file.get(recibidor_position).getAbsolutePath());
passIntent.putExtra("KEY",path);
sendBroadcast(passIntent);
You have no set an action to the intent which you are broadcasting.
passIntent = new Intent("action");
In your case 'passIntent = new Intent(Constantes.ACTION.PREV_ACTION);` or whichever the action that you want to broadcast.
You can also use intent.setAction(action) to set an action.
you need to set action here.In manifest it is already registered
public void passData(){
passIntent = new Intent(this,Notification_Reciever.class);
passIntent.setAction("PLAY_ACTION"); path=String.valueOf(recibidor_file.get(recibidor_position).getAbsolutePath();passIntent.putExtra("KEY",path);
sendBroadcast(passIntent);
}
Here is an example of broadcast. do it like this
Intent intent = new Intent("IncomingChat");
intent.putExtra("visitor", String.valueOf(eventParameters[0]));
intent.putExtra("Action", "receivedincommingchats");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
and add this to the activity where you want to receive the broadcast
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(IncomingBroadcastReceiver, new IntentFilter("IncomingChat"));
}
private final BroadcastReceiver IncomingBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String Action = intent.getStringExtra("Action");
switch (Action){
case "receivedincommingchats":
String recVisit = intent.getStringExtra("visitor");
break;
default:
break;
}
}
};
Intent intent = new Intent();
intent.setAction("com.example.Broadcast");
intent.putExtra("data", "data");
sendBroadcast(intent);
your manifest file should have something like this ..
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="com.example.Broadcast" >
</action>
</intent-filter>
</receiver>
You have to register your broadcast receiver in your activity..
IntentFilter filter = new IntentFilter("com.example.Broadcast");
MyReceiver receiver = new MyReceiver();
registerReceiver(receiver, filter);
And your broadcast receiver will be like this
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Implement code here to be performed when
// broadcast is detected
}
}
I am new to android.
My project is having one activity and one service. My service is having one broadcast receiver and activity is having broadcast sender which is in PeriodSender method .Dynamically when i am registering the receiver then at the start of the service it is not invoking but if i send some thing after few moment then it invokes.
But I want to register it in Manifest ,I have included the receiver details in Manifest but the receiver is not invoking . My receiver class name is MyReceiver21 and the intent action is MY_ACTION1. actually I want my broadcast receiver to be registered at the starting it self.
Following is my Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.experiment.Test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="3"
android:targetSdkVersion="3" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.experiment.Test.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=".MyReceiver21" >
<intent-filter>
<action android:name="com.experiment.Test.MainActivity.MY_ACTION1" />
</intent-filter>
</receiver>
<service
android:name="Myservice21"
android:enabled="true" />
</application>
</manifest>
my activity code is
public class MainActivity extends Activity {
MediaPlayer OurSong;
Context SavedThis=this;
int i=0;
public Handler handler1 = new Handler();
public Handler handler2= new Handler();
Button Start;
Button Stop;
Button Button21;
Button StopButton;
public int GProgreess=0;
int Rc=0;
int BitCount=0;
int SeekPos=0;
int Period=500;
MyReceiver myReceiver;
final static String MY_ACTION1 = "MY_ACTION1";
public int Data=0;
public int beat=0;
int BreakVar=0;
Thread myThread ;
static public TextView text1,text2,text3,text4;
private SeekBar bar;
private TextView textProgress,textAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StopButton=(Button)findViewById(R.id.buttonstop);
StopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
stopService(new Intent(SavedThis,Myservice21.class));
BitCount=0;
}/****End of on clk******/
});/*****End of set on clk listener*****/
Button21.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Rc=0;
BitCount=13;
stopService(new Intent(SavedThis,Myservice25.class));
SystemClock.sleep(200);
startService(new Intent(SavedThis,Myservice21.class));
PeriodSender();
}/****End of on clk******/
});/*****End of set on clk listener*****/
}
public void PeriodSender()
{
Intent intent1 = new Intent();
intent1.setAction("MY_ACTION1");
intent1.putExtra("kz", Period);
sendBroadcast(intent1);
text3.setText(""+Period);
Toast.makeText(getApplicationContext(), "PeriodSent",Toast.LENGTH_SHORT).show();
}
#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;
}
}
my service class
public class Myservice21 extends Service {
int BitCount=0;
int Rc=0;
int Period=500;
Intent intent = new Intent();
MyReceiver21 myReceiver21;
public Handler handler1 = new Handler();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
intent.setAction(MY_ACTION);
myReceiver21 = new MyReceiver21();
IntentFilter intentFilter1 = new IntentFilter();
intentFilter1.addAction(com.experiment.Test.MainActivity.MY_ACTION1);
registerReceiver(myReceiver21, intentFilter1);
Intent intent1 = new Intent(Myservice21.this,MainActivity.class);
startService(intent1);
handler1.post(runnable1);
}
public class MyReceiver21 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
int data = intent.getIntExtra("kz", 0);
Period=data;
Toast.makeText(getApplicationContext(), "PeriodRceived21",Toast.LENGTH_SHORT).show();
}
}
public void onStart(Intent intent,int StartId)
{
Rc=0;
}
public void onDestroy()
{
}
}
can any one help me to register the receiver in manifest. Thanks in advance
You don't have to add the intent filter for your own broadcasts. Just register the service for that broadcasts with registerReceiver() when the service is started.
Note, that you have to start the service manually when your App starts, for instance in the MainActivity.onCreate():
startService(new Intent(this, Myservice21.class));
When the MainActivity has been created, it will start the service, which itself registers for BroadcastIntents and starts listening for them. This should work.
How would I get my app to listen for when DayDream stops. When the system stops dreaming it sends the ACTION_DREAMING_STOPPED string out. I have added a BroadcastReceiver in my OnResume and onCreate and neither are used when DayDream stops. So where should I put my listener? I do apologize if I am calling something by its wrong name, I haven't worked with DayDream before.
#Override
protected void onResume() {
mDreamingBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_DREAMING_STOPPED)) {
// Resume the fragment as soon as the dreaming has
// stopped
Intent intent1 = new Intent(MainActivity.this, MainWelcome.class);
startActivity(intent1);
}
}
};
super.onResume();
}
The BroadcastReceiver can be created in your onCreate.
Ensure you register the receiver with: registerReceiver(receiver, filter) and that you've got the intent-filter inside your AndroidManifest.xml.
Sample:
MainActivity.java
public class MainActivity extends Activity
{
private static final String TAG = MainActivity.class.toString();
private BroadcastReceiver receiver;
private IntentFilter filter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, TAG + " received broacast intent: " + intent);
if (intent.getAction().equals(Intent.ACTION_DREAMING_STOPPED)) {
Log.d(TAG, "received dream stopped");
}
}
};
filter = new IntentFilter("android.intent.action.DREAMING_STOPPED");
super.registerReceiver(receiver, filter);
}
}
AndroidManifest.xml
<activity
android:name="com.daydreamtester.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.DREAMING_STOPPED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
I'm trying to deal with push notifications in my main class (and i also have GCMBroadcastReceiver - for all the notifications that comes when i'm not running the main class)
but the registerReceiver Does not work
(GCMBroadcasrReceiver works fine)
my code:
public class Main extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(mHandleMessageReceiver, new IntentFilter("com.google.android.c2dm.intent.RECEIVE"));
}
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadcastReceiver","Working");
}
};
}
Manifest:
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
</intent-filter>
</receiver>
*Works fine only in my 4.1.2 (S3)
Well, found the solution:
in my GCMIntentService.java i need to set sendBroadcast like so:
#Override
protected void onMessage(Context context, Intent intent) {
Intent i = new Intent("com.my.app.DISPLAY_PUSH");
i.putExtra("msg", intent.getExtras().getString("msg"));
context.sendBroadcast(i);
}
and the BroadcastReceiver should be
protected void onCreate(Bundle savedInstanceState) {
registerReceiver(mHandleMessageReceiver, new IntentFilter("com.my.app.DISPLAY_PUSH"));
}
.
.
.
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadcastReceiver","Working with msg:" + intent.getExtras().getString("msg") );
}
};
I wonder why it works in 4.1.2 without the sendBroadcast...
if you call sendBroadcast like this
Intent intent = new Intent(context, mBroadcastReceiver.getClass());
intent.setAction(ACTION_ON_CLICK);
context.sendBroadcast(intent);
// or
Intent intent = new Intent(context, MyBroadcastReceiver.class);
intent.setAction(ACTION_ON_CLICK);
context.sendBroadcast(intent);
change it to this :
Intent intent = new Intent(ACTION_ON_CLICK);
context.sendBroadcast(intent);
I would like to start a broadcast receiver from an activity. I have a Second.java file which extends a broadcast receiver and a Main.java file from which I have to initiate the broadcast receiver.
I also tried doing everything in Main.java as follows but didn't know how to define in manifest file...
Main.java:
public class Main extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String rec_data = "Nothing Received";
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if( intent.getStringExtra("send_data")!=null)
rec_data = intent.getStringExtra("send_data");
Log.d("Received Msg : ",rec_data);
}
};
}
protected void onResume() {
IntentFilter intentFilter = new IntentFilter();
//intentFilter.addDataType(String);
registerReceiver(myReceiver, intentFilter);
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.unregisterReceiver(this.myReceiver);
}
}
If I cannot do everything in one class as above, how can I call the Broadcast Receiver from Main.java? Can anyone please let me know where I'm doing it wrong? Thanks!
use this why to send a custom broadcast:
Define an action name:
public static final String BROADCAST = "PACKAGE_NAME.android.action.broadcast";
AndroidManifest.xml register receiver :
<receiver android:name=".myReceiver" >
<intent-filter >
<action android:name="PACKAGE_NAME.android.action.broadcast"/>
</intent-filter>
</receiver>
Register Reciver :
IntentFilter intentFilter = new IntentFilter(BROADCAST);
registerReceiver( myReceiver , intentFilter);
send broadcast from your Activity :
Intent intent = new Intent(BROADCAST);
Bundle extras = new Bundle();
extras.putString("send_data", "test");
intent.putExtras(extras);
sendBroadcast(intent);
YOUR BroadcastReceiver :
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
if (extras != null){
{
rec_data = extras.getString("send_data");
Log.d("Received Msg : ",rec_data);
}
}
};
for more information for Custom Broadcast see Custom Intents and Broadcasting with Receivers
check this tutorial here you will get all help about broadcast including how to start service from activity or vice versa
http://www.vogella.de/articles/AndroidServices/article.html
For that you have to broadcast a intent for the receiver, see the code below :-
Intent intent=new Intent();
getApplicationContext().sendBroadcast(intent);
You can set the action and other properties of Intent and can broadcast using the Application context, Whatever action of Intent you set here that you have to define in the AndroidManifest.xml with the receiver tag.
Check this answer:
https://stackoverflow.com/a/5473750/928361
I think if you don't specify anything in the IntentFilter, you need to tell the intent the receiver class.