passing a variable from a service to a broadcast receiver - android

Hello guys i am trying to send two variables from an android service to a broadcast receiver, and i need help here..
i am setting up two var's in the oncreate method of the service class here..
#Override
public void onCreate() {
super.onCreate();
Intent eSendIntent = new Intent(getApplicationContext(), OutgoingCallReceiver.class);
eSendIntent.putStringArrayListExtra("BlockArray", contactsListB);
eSendIntent.putExtra("BlockBool", checkB);
getApplicationContext().sendOrderedBroadcast(eSendIntent, null);//Call receiver
}
and in my receiver class...
onReceive(Context context, Intent intent){
Bundle bundle = intent.getExtras();
if(bundle == null)
return;
boolean cb = bundle.getBooleanExtra("BlockBool", true);
ArrayList<String> ab = bundle.getStringArrayListExtra("BlockArray");
//disconnecting
try{
if(cb==false){
for(int ij = 0; ij < ab.size(); ij++){
if(ab.get(ij).contains(phonenumber)){
tempBoolean = true;
//Log.e("OutgoingCallReceiver", SmsBlockerService.contactsListB.get(ij));
}
}//for loop
if(tempBoolean==true){
setResultData(null);
Toast.makeText(context, phonenumber + " is Blocked", Toast.LENGTH_SHORT).show();
}
}else{
setResultData(null);
Toast.makeText(context, "All Out-Going Calls are Blocked", Toast.LENGTH_SHORT).show();
}//end of main if
} catch(Exception e){
Toast.makeText(context, "Detect Calls sample application Failed: ", Toast.LENGTH_LONG).show();
}
}
logcat:
E/BroadcastReceiver(1459): BroadcastReceiver trying to return result during a non-ordered broadcast

set this in your broadcast intent
i.setAction("MYACTION");
than set this in your manifest
<receiver android:name=".BroadcastClass" >
<intent-filter>
<action android:name="MYACTION" />
</intent-filter>
</receiver>
may be this should helpful

Assuming that you registered the receiver.Now try to make a small change:
boolean cb = bundle.getBooleanExtra("BlockBool", true);
ArrayList<String> ab = bundle.getStringArrayListExtra("BlockArray");
Update:
In the on create... call the broadcast like...
sendOrderedBroadcast(eSendIntent);
You are facing that error because , setResultData() function works only with OrderedBroadcast.
From Android Documentation:
public final void setResultCode (int code)
Added in API level 1
Change the current result code of this broadcast; only works with broadcasts sent
through Context.sendOrderedBroadcast. Often uses the Activity RESULT_CANCELED and
RESULT_OK constants, though the actual meaning of this value is ultimately up to the
broadcaster.
This method does not work with non-ordered broadcasts such as those sent with
Context.sendBroadcast.

for broadcast receiver to work the activity/screen in which it is written should be up & running. so that receiver can receives the passed intent & it's value.

Related

Running tasks from broadcast receiver while app is closed [Android]

I have an app that downloads data and put it into an SQLite Database when a notification is issued. This works fine while the app is in use but I need it to work when the app is closed too.
I have set up a BroadcastReceiver within that is called when the app is closed but I'm not sure how to get it to continue with adding to the database.
Here is the code I am using:
AndroidManifest.xml
<manifest....
<application...
<receiver android:name=".broadcast.PacksReceiver" >
<intent-filter>
<action android:name="ADD_PACK" >
</action>
</intent-filter>
</receiver>
PacksReceiver
public class PacksReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("PacksReceiver", "onReceive");
String message = intent.getStringExtra("message");
PacksActivity pa = new PacksActivity();
pa.downloadPack(null, message);
}
}
PacksActivity
public void downloadPack(View v, String thisPackID){
Log.d("download", "pack");
//THIS LOG IS CALLED EVERYTIME
vRef = v;
if(vRef != null){
runOnUiThread(new Runnable() {
#Override
public void run() {
onScreenProgressBar = (ProgressBar) vRef.findViewById(R.id.onScreenProgress);
onScreenProgressCircle = (ProgressBar) vRef.findViewById(R.id.onScreenProgressCircle);
dlPercent = (TextView) vRef.findViewById(R.id.dlPercent);
onScreenProgressCircle.setVisibility(View.VISIBLE);
onScreenProgressBar.setVisibility(View.VISIBLE);
onScreenProgressCircle.setProgress(0);
}
});
}
if(thisPackID == null){
thisPackID = pack_id;
}
String url = MyApp.getAppContext().getString(R.string.serverURL) +
MyApp.getAppContext().getString(R.string.getAppendixA) + "/" + thisPackID;
Intent appA_Intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);
appA_Intent.putExtra("url", url);
appA_Intent.putExtra("onCreate", "false");
appA_Intent.putExtra("receiver", downloadPackReceiver);
appA_Intent.putExtra("downloadType", "GET_APPENDIX_A");
appA_Intent.putExtra("requestId", 101);
MyApp.getAppContext().startService(appA_Intent);
}
start the Service from
onReceive()
method because you can get mutiple broadcast one after another.
Write the code to add data in your database in your PackReciever inside OnRecieve() Method because that is where you recieve push notifications.
Don't call activity inside the receiver. Instead, use IntentService to download all packs. IntentService automatically finishes once it completes its work.
Override its onHandleIntent() method and download packs and save to database there.

Android background BroadcastReceivers but dynamically create

I'm currently trying to get broadcast receivers running in the background of my android application, which I've been told to use an event service for. At present my broadcast receivers work fine if you're in the activity within which they're registered
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW)) {
Toast.makeText(arg0, "Battery's dying!!", Toast.LENGTH_LONG).show();
Log.e("LOW", "LOW");
intent = null;
}else if(intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {
Toast.makeText(arg0, "Battery's discharging!!", Toast.LENGTH_LONG).show();
Log.e("discharge", "discharge");
intent = null;
}else if(intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(arg0, "Battery's charging!!", Toast.LENGTH_LONG).show();
Log.e("charge", "charge");
intent = null;
}else if(intent.getAction().equals(Intent.ACTION_BATTERY_OKAY)) {
Toast.makeText(arg0, "Battery's okay!!", Toast.LENGTH_LONG).show();
Log.e("OKAY", "OKAY");
intent = null;
}
}
};
in OnCreate:
registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_LOW));
registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_OKAY));
registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_POWER_CONNECTED));
Despite the issues that arise with leaking intentfilters by making them in oncreate, my current issue that that when I change activity these no longer run, I've read from the following: http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#startingservices_alarmmanager
That by placing these into an IntentService and starting this service, they'll run consistently, however this involves registering the receivers in the manifest, which gives me issues in that my application is planning on allowing the user to listen out for specific events IE: these cannot be created dynamically.
Is there a way to dynamically create broadcast receivers within a class, which runs in the background of the application and is triggered when the broadcast occurs?

I want my android app to start when a phone receives a call and to get the incoming phone number

I want my android app to start when a phone receives a call and to get the incoming phone number, i what to be able to put button on the screen of the incoming call and before that to be able to get the number calling, it would be of much help i anyone can refer me to some examples or materials. thx
You can setup a broadcastlistener in your AndroidManifet.xml You must setup your intent to listen for android.intent.action.PHONE_STATE
Then you get the phone state from the intent with intent.getExtraString(TelephonyManager.EXTRA_STATE) . If it's OFFHOOK or RINGING then a call has come in and you can get the phone number from the intent with intent.getExtraString(TelephonyManager.EXTRA_INCOMING_NUMBER)
This will toast and log the incomming number...
public class CallReceiveD extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.w("DEBUG", state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String phoneNumber = extras
.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast toast= Toast.makeText(context,phoneNumber, Toast.LENGTH_LONG);toast.show();
Log.w("DEBUG", phoneNumber);
}
}
}
}
dont forget the manifest file
< receiver
android:name=".CallReceiveD">
< action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>

Passing Data from Broadcast Receiver to another Activity

Hi I've been having an issue with Broadcast Receivers and passing information to another activity. I'm trying to create an application that will capture incoming SMS messages, look for a website in the text, then pop up an Alert Dialog box asking if the user wants to go to the website.
public class TextReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent)
{
// .. other code that
// sets received SMS into message
Toast toast = Toast.makeText(context,
"Received Text: " + message.getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
So that code works fine, receive a text it pops up a toast with the message. The toast is useless but it shows the receiver works. But I want to communicate with an activity to show an Alert Dialog and start up a webView. I already programmed the code that will take a string search for the website and open the webView. Is it possible to get the string from the broadcast receiver and do something like this?:
public class ReceiveText extends Activity{
public void onCreate(Bundle savedInstanceState) {
// Somehow pass the string from the receiver into this activity,
//stored in variable messages
findOpen(messages);
// is that possible?
}
public class findOpen(string messages){
// do stuff ... open alert...open site if OK
}
So basically I just want to pass a string from a Broadcast Receiver to another activity that will use that string. The rest of the code is basically in place all I need is that string... I'm new to this and Java and any help would be much appreciated. Thanks
Instantiate a BroadcastReceiver in the activity you want to get your data to, for example:
private BroadcastReceiver mServiceReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent)
{
//Extract your data - better to use constants...
String IncomingSms=intent.getStringExtra("incomingSms");//
String phoneNumber=intent.getStringExtra("incomingPhoneNumber");
}
};
Unregister your receiver on onPause():
#Override
protected void onPause() {
super.onPause();
try {
if(mServiceReceiver != null){
unregisterReceiver(mServiceReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Register it on onResume():
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.SmsReceiver");
registerReceiver(mServiceReceiver , filter);
}
Broadcast your data from the service via an Intent, for Example:
Intent i = new Intent("android.intent.action.SmsReceiver").putExtra("incomingSms", message);
i.putExtra("incomingPhoneNumber", phoneNumber);
context.sendBroadcast(i);
and that's it! goodLuck!
If you have your activity named ReceiveText, then in your BroadcastReceiver, you should do the following:
Intent i = new Intent(context, ReceiveText.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("message", message.getMessageBody());
context.startActivity(i);
Then, in your activity, you will need to getExtra as so:
Intent intent = getIntent();
String message = intent.getStringExtra("message");
And then you will use message as you need.
If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="#android:style/Theme.Dialog" /> in your manifest for ReceiveText and then set the message to a textview in the activity.
EDIT: This restarts your activity. this answer is likely a better solution for most people.
We can send the data from onReceive to another activity using LocalBroadcastManager.
It means you are again broadcasting the data using the context
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Broadcast", "wifi ConnectivityReceiver");
Bundle extras = intent.getExtras();
Intent intent = new Intent("broadCastName");
// Data you need to pass to another activity
intent .putExtra("message", extras.getString(Config.MESSAGE_KEY));
context.sendBroadcast(intent );
}

android Broadcastreceiver issue

Im developing an application,which blocks all outgoing calls and then after blocking that call ,another new call is initiated to a predefined number...
My problem is that,when i block the call using a broadcastreceiver,the second call which i programmatically initiate is also getting blocked...
Is any method to unregister the broadcast after blocking the first call,or any other method or technique???
This is my broadcastreceiver which i implemented for my app...
public class CallListenerActivity extends BroadcastReceiver {
Uri uri;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle == null)
return;
String phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i("###OutgoingCallReceiver",phonenumber);
Log.i("###OutgoingCallReceiver",bundle.toString());
String info = "Detect Calls sample application\nOutgoing number: " + phonenumber;
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
String phoneNumber = "5556";
Uri uri = Uri.fromParts("tel", phoneNumber, null);
Intent callIntent = new Intent(Intent.ACTION_CALL, uri);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
}
You could try starting your original (CallListenerActivity? The one which registered the broadcast receiver) activity again using a flag stored as extra in the intent.
Evaluate the intent in your activity and unregister the broadcast receiver if you see the flag in the extras. Then start the the call activity as shown in your example code.
You can use store a check when you are initiating a call and after the completion of the call mark it. For this this check you can use SharedPreference.

Categories

Resources