The receiver is not receiving broadcast in android studio - java

The receiver is not receiving the broadcast from the sender. I just created a button and on that button i created an on click event. When This event is called the Sender will send broadcast to all apps in android phone.
.xml file of Main Activity
The code used in used in main MainActivity to send Broadcast is;
package com.example.mk141.sendbroadcast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void send_broadcast(View view)
{
Intent i=new Intent();
i.setAction("com.example.mk141.sendbroadcast");
i.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
}
}
The Code used in Receiver to display a Toast on receiving the broadcasts is;
package com.example.mk141.recievebroadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{
}
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context,"The Broadcast has been
recieved!",Toast.LENGTH_LONG).show();
}
}
I also Changed the code in Android Manifest so that Receiver only receives broadcast against a specific action;
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mk141.recievebroadcast">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter >
<action android:name="com.example.mk141.sendbroadcast">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
But when i run both sender and receiver then no Toast text is shown on pushing SEND BROADCAST button. Please anyone help me in solving this issue thanks!

Related

Call method when Application Closes

I know this is asked many times, but I want to clear things up
In which activity should I place onDestroy()? Say I am in the MainActivity A and I move to activity B. But then I close the application while being on activity B. Does the onDestroy() method in MainActivity A get called? Or should I put an onDestroy() method for every activity in the application? Or is there any other way around this?
I have tried reading documentation and reading other answers but they don't help me clearly.
There are multiple ways to do so , Here I have mentioned the most reliable way I have found during development carrier . You need to create a Service which can keep an eye whether application got closed or not, so here I have mentioned the code !
1.Create Service , as you can see below there is a new class named as MyService, this needs to extended to Service.
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(getClass().getName(), "App just got removed from Recents!");
}
}
2.Add this entry to Manifest.xml as below ...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
>
<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/Theme.TestApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
</manifest>
3.This is Just a Service that will run in background , but we need to start it once the application starts , so in your launcher activity start it like below.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent stickyService = new Intent(this, MyService.class);
startService(stickyService);
}
}
4.Service will start and whenever User will Swipe out the application from recent , the function onTaskRemoved will be called automatically , in this function you can put your required work or code to be executed at the application end !

How to Pass Data From a BroadcastReceiver to an Activity in Android

I am working on my first Android app, which is a paging device. It will intercept a SMS message from a certain number with a certain content in it, display that and then allow the user to send a pre-defined reply back to that same number. I have gathered up code snippets from numerous sources (including stackoverflow of course) but I haven't yet got it working.
My file structure is as shown here
The part I am struggling with is SmsBroadcastReceiver and ReceiveAlert, which should display the content of the SMS and has a button to initiate the reply.
SmsBroadcastReceiver.java looks like this:
package com.example.alert6;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String EXTRA_MESSAGE = "com.example.alert6.MESSAGE";
#Override
public void onReceive(Context context, Intent intent) {
String smsSender = "";
String smsBody = "";
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.getOriginatingAddress();
smsBody = smsMessage.getMessageBody();
}
if (smsSender.equals("+420775367297")) {
if (smsBody.contains("Test")) {
intent.putExtra(EXTRA_MESSAGE, smsBody);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // adding this flag starts the new Activity in a new Task
context.startActivity();
}
}
}
}
ReceiveAlertActivity.java is this:
package com.example.alert6;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ReceiveAlertActivity extends AppCompatActivity {
private static final int SMS_PERMISSION_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_alert);
}
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String taskingalert = intent.getStringExtra(SmsBroadcastReceiver.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView receivedAlert = findViewById(R.id.receivedAlert);
receivedAlert.setText(taskingalert);
public boolean respond(View view) {
if (!hasReadSmsPermission()) {
requestReadAndSendSmsPermission();
return false;
}
Intent intent = new Intent(this, SendResponseActivity.class);
startActivity(intent);
return false;
}
/**
* Runtime permission shenanigans
*/
private boolean hasReadSmsPermission() {
return (ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED);
}
private void requestReadAndSendSmsPermission() {
ActivityCompat.requestPermissions(ReceiveAlertActivity.this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.SEND_SMS},
SMS_PERMISSION_CODE);
}
}
And the manifest is this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.alert6">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<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/Theme.Alert6">
<activity
android:name=".SendResponseActivity"
android:parentActivityName=".ReceiveAlertActivity">
</activity>
<activity
android:name=".ReceiveAlertActivity"
android:parentActivityName=".MainActivity">
</activity>
<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=".SmsBroadcastReceiver"
android:enabled="true"
android:exported="true"
tools:ignore="Instantiatable">
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Android Studio is showing errors in SmsBroadcastReceiver and ReceiveAlertActivity but not giving enough information to resolve them.
In SmsBroadcastReceiver, it tells me it cannot resolve method 'startActivity()'. Something needs to go in the brackets, but what?
In ReceiveAlertActivity the problems revolve around receivedalert and taskingalert. It cannot resolve setText because taskingalert is an unknown class. Obviously it's not a class, it's a string so I'm doing something wrong, but what?
Sorting out these problems may not be the end. At the moment I can't test if the app works because the build fails due to the above. Then if I get this lot working, I have some other challenges, like waking up the screen and playing a sound the broadcast receiver is triggered, and stopping the sound when the button is pressed.
You can use an Observable object in your BroadcastReceiver to store the piece of information you want to send and implement the Observer interface in your Activity so that it will be warned of every change occuring to the Observable object.

How to Listen for Bluetooth Headset Buttons in an Android App?

What is the proper way to handle Bluetooth media buttons in an Android app? At this point, all I want is an event to fire when I press the pause/play button on my Bluetooth headset. Somehow, I had a working solution yesterday, and today it just doesn't work. Without reinstalling the app, or any update happening on my phone, the onReceive method of my subclass of BroadcastReceiver is never entered. I'm targeting Android 9.0, since this is just for myself.
I used the information in these two questions for the solution:
How to capture key events from bluetooth headset with android
BroadcastReceiver for ACTION_MEDIA_BUTTON not working
This is a bare minimum version of what was working yesterday, which currently does not work:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission android:name="android.permission.BLUETOOTH" />
<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"
tools:ignore="GoogleAppIndexingWarning">
<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=".MediaButtonIntentReceiver">
<intent-filter android:priority="2139999999">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
AudioManager mAudioManager = null;
ComponentName mReceiverComponent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mReceiverComponent = new ComponentName(this, MediaButtonIntentReceiver.class);
mediaFilter.setPriority(2139999999);
registerReceiver(mMediaButtonReceiver, mediaFilter);
}
}
MediaButtonIntentReceiver.java
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
Log.i("mylog", "init");
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("mylog", "receive");
abortBroadcast();
}
}

Why the Broadcast receiver is not working dynamicly?

I tried to do a broadcast receiver dynamically for incoming SMS will show a toast but the app doesn't show anything.
I register the broadcast dynamically in the mainActivity like this.
MainActivity.java
package com.example.smsreader;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
BroadcastReader reader = new BroadcastReader();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(reader, filter);
}
}
This is brodcast class, the app will show a toast when the phone will receive a SMS but it doesn't
package com.example.smsreader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BroadcastReader extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())){
Toast.makeText(context, "it is working", Toast.LENGTH_LONG).show();
}
}
}
I don't register anything in the manifest file.
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smsreader">
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<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>
Try the following :
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
You need to use the following method for registering local broadcastReceiver ;)
LocalBroadcastManager.getInstance(this).registerReceiver(reader, filter)

Unlock Android device programmatically and load application on boot up

Objective: Unlock Android device programmatically and load application on boot up
API: 10 & 18
IDE: Eclipse
Test device: Emulator
I understand this issue has been widely discussed on stackoverflow and elsewhere. But I am unable to get this to work. My first question is
Can the Emulator be programmatially unlocked and an application be loaded on boot up?
I also read that after API 13 some there were some changes and I am not sure if I am accounting for these changes
Assuming the answer is yes please find code excepts below.
AndroidManifest.xml
<manifest
package="com.example.display">
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.display.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="com.example.display.myreceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
MainActivity.java
package com.example.display;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Unlock
// http://developer.android.com/reference/android/app/Activity.html#getWindow()
Window window = getWindow();
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
#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;
}
}
myreceiver.java
I am expecting this section of the code to get executed on boot up and start the application.
package com.example.display;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class myreceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(myIntent);
}
}
Issue: I have loaded the above code to the emulator and re-started the emulator. I was expecting the code application to unlock the emulator and load the application of boot up. It doesn't happen...
Not sure where to look for next...
Most of the code snippets are from on stackoverflow.
Some of the post that I have referenced are
Trying to start a service on boot on Android
How to launch the application upon booting up the device?
Android - Wake Up and Unlock Device
Thank you in advance.
Hi here i added the unlock programmatically and launch our application using the below code.You need to add the unlock code in broadcast receiver.
Please try and let me. Thanks
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
public class myreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Unlock the screen
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "INFO");
wl.acquire();
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock kl = km.newKeyguardLock("name");
kl.disableKeyguard();
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(myIntent);
}
}

Categories

Resources