I am creating a app which can detetct incomming sms to android phone but app is not working in background.
Here is my mainactivity.java in which i am asking for the permission from user to allow access to read sms.
package com.example.times;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int READ_SMS_PERMISSION=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECEIVE_SMS))
{
// do nothing
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, READ_SMS_PERMISSION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch(requestCode)
{
case READ_SMS_PERMISSION:
{
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Thankyou for granting access", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "No problem", Toast.LENGTH_LONG).show();
}
}
}
}
}
Here is myreciver.java in which i am detecting incomming sms and making toast of that msg.
When app is opened then it is working properly but when i exit the app it is not detecting any sms.
package com.example.times;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
private static final String TAG="SmsBroadcastReceiver";
String msg, phoneNo ="";
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// throw new UnsupportedOperationException("Not yet implemented");
Log.i(TAG, "Intent Received: " +intent.getAction());
if (intent.getAction()==SMS_RECEIVED)
{
Bundle dataBundle = intent.getExtras();
if (dataBundle!=null)
{
Object[] mypdu=(Object[])dataBundle.get("pdus");
final SmsMessage[] message = new SmsMessage[mypdu.length];
for (int i =0; i<mypdu.length; i++)
{
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
{
String format= dataBundle.getString("format");
message[i] = SmsMessage.createFromPdu((byte[])mypdu[i],format);
}
else
{
message[i] = SmsMessage.createFromPdu((byte[]) mypdu[i]);
}
msg =message[i].getMessageBody();
phoneNo= message[i].getOriginatingAddress();
}
Toast.makeText(context, "Message: " +msg +"\nNumber: " +phoneNo, Toast.LENGTH_SHORT).show();
}
}
}
}
Telll me if i am doing something wrong.
Make sure you have these in your Android Mainfest.xml
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
And the following
<receiver
android:name=
"com.example.times.MyReceiver"
android:enabled="true"
android:exported="true">
</receiver>
EDIT
You need an Intent Service to read sms while your app is closed or in background.
Intent Service - Run in Background
Steps:
Create Intent Service
Add it Manifest
Call it from your Broadcast Receiver onReceive() method via Intent
Related
In android 12 api 31
I run this app ,it doesn't work properly
I want to find the name of the nearby devices but the Bluetooth device doesn't start until I click on the Bluetooth button from the notification panel and in log it shows Discovery Started and Gave another Log which shows Discovery Finished without searching a device.
package com.aditya.bluetoothfinder;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ListView listView;
TextView statusTextView;
Button searchButton;
BluetoothAdapter bluetoothAdapter;//The BluetoothAdapter is required for any and all Bluetooth activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
statusTextView = findViewById(R.id.statusTextView);
searchButton = findViewById(R.id.searchButton);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
public void searchClicked(View view) {
if (bluetoothSupported()) {
openBluetooth();
} else {
statusTextView.setText("Bluetooth Not Supported");
}
}
//This function will check that the bluetooth is supported on the device or not
public boolean bluetoothSupported() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
}
//This function opens the bluetooth
public void openBluetooth() {
if (!bluetoothAdapter.isEnabled()) {
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
requestThePermissons();
} else {
startActivityForResult(enableBluetoothIntent, 1);
}
} else {
searchBluetoothDevices();
}
}
//This function request the permission
private void requestThePermissons() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { //if we don't have any permission
requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_CONNECT);
} else { //if we already have permissionn of bluetooth connect
searchBluetoothDevices();
}
}
//This is a callback which give us the information that the user gave us the permission or not
private final ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
// Permission is granted. Continue the action or workflow in your
searchBluetoothDevices();
} else { //If user declined the permission request
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
});
//This is the function for searching bluetooth devices
public void searchBluetoothDevices() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Unable to locate bluetooth device", Toast.LENGTH_SHORT).show();
requestPermissions(new String[]{Manifest.permission.BLUETOOTH_SCAN},1);
} else {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Unable to locate", Toast.LENGTH_SHORT).show();
}
bluetoothAdapter.startDiscovery();
statusTextView.setText("Searching...");
searchButton.setEnabled(false);
}
}
When I call the bluetoothAdapter.startDiscovery();
It shows
D/BluetoothAdapter: startDiscovery(): called by: com.aditya.bluetoothfinder
but doesn't show the log Discovery started until I click on the Bluetooth button from the notification panel and after that it gives another Log Discovery Finished
//This function give us the details of the bluetooth device if found
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.i("this", "Device Found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
requestThePermissons();
Toast.makeText(MainActivity.this, "Unable to find", Toast.LENGTH_SHORT).show();
} else {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
String text = (String) statusTextView.getText();
statusTextView.setText(text + "\n" +deviceName + "\n" + deviceHardwareAddress);
}
} else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.i("this", "Discovery Finished");
statusTextView.setText("Finished");
searchButton.setEnabled(true);
} else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.i("this", "Discovery started");
Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
}
}
};
}
Permission used in AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/>
You also have to take location permission from the user and the user has to turn on location services in order to see other Bluetooth devices.
I've been playing around with some Android recently and have the following setup:
I have app A, which is a service. This has no activity. Here's its manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sandbox.sampleservice">
<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.SampleService">
<service
android:name=".DummyService"
android:exported="true"
android:enabled="true">
</service>
</application>
</manifest>
and here's the Java code:
package com.sandbox.sampleservice;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
public class DummyService extends Service {
private static final String TAG = "DummyService";
static class MessageHandler extends Handler {
#Override
public void handleMessage(Message msg) {
// TODO: sort this later
super.handleMessage(msg);
}
}
Messenger mMessenger = null;
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "Binding");
mMessenger = new Messenger(new MessageHandler());
return mMessenger.getBinder();
}
#Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "No longer bound");
return false;
}
}
I then have an app B with an empty activity which I want to bind to the service in app A. This is it's MainActivity:
package com.sandbox.sampleclient;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SampleClient";
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "Bound");
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "Unbound");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.sandbox.sampleservice", ".DummyService"));
boolean result = this.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
if (result) {
Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "failed", Toast.LENGTH_SHORT).show();
}
}
}
I'm running on the default emulator that comes with Android Studio - API 30/x86.
I've installed the service using the installDebug Gradle task and can see the app in the Settings. But running app B, the call to bindService() returns false (it shows the failure toast). And I have the following message in logcat:
2021-04-03 20:33:59.743 500-1764/system_process W/ActivityManager: Unable to start service Intent { cmp=com.sandbox.sampleservice/.DummyService } U=0: not found
I've tried a few things - using the app context rather than the activity one when binding, using the fully qualified class name, and more. No change in behaviour, and the error in logcat is always the same.
Currently making a Location Service for an app I'm currently building. I'm trying to print the obtained latitude and longitude through a Log and through a Toast.makeText from a broadcast receiver but nothing is showing when I run. Was hoping if you guys could see any faults.
LocationService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
public class LocationService extends Service {
FusedLocationProviderClient fusedLocationProviderClient;
LocationCallback locationCallback;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback(){
// Whenever there is a Location Update, this method is where it occurs
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
// Log Result for Longitude and Latitude, call method to receive elsewhere
Log.d("Location Log", "Latitude is: " + locationResult.getLastLocation().getLatitude() +
"Longitude is: " + locationResult.getLastLocation().getLongitude());
Intent intent = new Intent("ACT_LOC");
intent.putExtra("Latitude", locationResult.getLastLocation().getLatitude());
intent.putExtra("Longitude", locationResult.getLastLocation().getLongitude());
sendBroadcast(intent);
}
};
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
requestLocation();
return super.onStartCommand(intent, flags, startId);
}
// Method to request the Location every 3 seconds
private void requestLocation(){
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback,
Looper.myLooper());
}
}
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT >= 23){
// If the permission Access Fine Location is not granted
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
// Request Location
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else{
// Request Location Permission
startService();
}
}
else{
// Start Location Service
startService();
}
}
// Start the service with a new intent for the MainActivity and Location Services
// Register Broadcast Receiver with intent action from LocationService.java
void startService(){
LocationBroadcastReceiver receiver = new LocationBroadcastReceiver();
IntentFilter filter = new IntentFilter("ACT_LOC");
Intent intent = new Intent(MainActivity.this, LocationServices.class);
startService(intent);
registerReceiver(receiver, filter);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case 1:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
startService();
}
else{
Toast.makeText(this, "Give me permissions", Toast.LENGTH_LONG).show();
}
}
}
public class LocationBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// check if action is required or not
if(intent.getAction().equals("ACT_LOC")){
double lat = intent.getDoubleExtra("Latitude", 0f);
double lng = intent.getDoubleExtra("Longitude", 0f);
Toast.makeText(MainActivity.this, "Latitude is: " + lat + ", Longitude is: " + lng, Toast.LENGTH_LONG).show();
}
}
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anongeolocation">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<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>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.MAIN"/>
</intent-filter>
</activity>
<service android:name=".LocationService"/>
</application>
</manifest>
Any help would be greatly appreciated. Thanks in advance.
If log or toast doesnt run it could only have one reason.the compiler doesnt get into their methods somehow.i suggest you log everywhere compiler can go from on create of main activity and follow logs one by one to find out where exactly compiler is!
Today I started writing for android. I want a simple (I think) app that waits for notification with specified title and then does something. I tried this code for service
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
public class NotificationListener extends NotificationListenerService {
Context context;
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
Toast.makeText(this,"NOTIFICATION",Toast.LENGTH_SHORT).show();
String text = "";
String title = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
Bundle extras = extras = sbn.getNotification().extras;
text = extras.getCharSequence("android.text").toString();
title = extras.getString("android.title");
}
Log.i("Package",pack);
Log.i("Title",title);
Log.i("Text",text);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Toast.makeText(this,"NOTIFICATION removed",Toast.LENGTH_SHORT).show();
Log.i("Msg","Notification was removed");
}
}
Then added this to manifest:
<service
android:name=".NotificationListener"
android:enabled="true"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
finally started the service in MainActivity onCreate() startService(new Intent(context, NotificationListener.class));
onNotificationPosted does not work. It seems like service was started correctly, because toasts from onStartCommand and onCreate were shown. I tried on emulator and real device. I also allowed notification access in settings. Please help, I wasted 5 hours on that.
I have made small app for Android mobile.
In one situation I am not getting any solution.
Actually my app has small functionality for calling to customer.
So after call ended I need that event of which last number will dialed or which app is runs.
AndroidManifest:
<receiver android:name=".PhoneStateBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE">
</action></intent-filter>
</receiver>
Add following permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE">
</uses-permission>
PhoneStateBroadcastReceiver.java (refactored the code a bit)
package com.mobisys.android.salesbooster;
import com.mobisys.android.salesbooster.database.HelperDatabase;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "PhoneStateBroadcastReceiver";
Context mContext;
String incoming_number;
private int prev_state;
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); //TelephonyManager object
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); //Register our listener with TelephonyManager
Bundle bundle = intent.getExtras();
String phoneNr = bundle.getString("incoming_number");
Log.v(TAG, "phoneNr: "+phoneNr);
mContext = context;
}
/* Custom PhoneStateListener */
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListener";
#Override
public void onCallStateChanged(int state, String incomingNumber){
if( incomingNumber != null && incomingNumber.length() > 0 )
incoming_number = incomingNumber;
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_STATE_RINGING");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_STATE_OFFHOOK");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_STATE_IDLE==>"+incoming_number);
if((prev_state == TelephonyManager.CALL_STATE_OFFHOOK)){
prev_state=state;
//Answered Call which is ended
}
if((prev_state == TelephonyManager.CALL_STATE_RINGING)){
prev_state=state;
//Rejected or Missed call
}
break;
}
}
}
}
Read more here, Source : http://mobisys.in/blog/2011/09/is-your-call-ended-on-android-phone/