startService() not running in android - android

I'm trying to run startService() in my android app, but it is not working.
Here is the code from the call to start the service:
Intent mPositioningIntent = new Intent(this, MyGeoloqiPositioning.class);
stopService(mPositioningIntent);
startService(mPositioningIntent);
Here is the code from MyGeoloqiPositioning.java (note, this is taken with minor modifications from the source code of MapAttack)
package com.example.manhunttwopointoh;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;
import com.example.manhunttwopointoh.MyFix;
import com.example.manhunttwopointoh.MyGeoloqiFixSocket;
import com.example.manhunttwopointoh.MyUDPClient;
public class MyGeoloqiPositioning extends Service implements LocationListener {
public static final String TAG = "GeoloqiPositioning";
private int batteryLevel = 0;
MyGeoloqiFixSocket fixSocket;
#Override
public void onCreate() {
android.os.Debug.waitForDebugger();
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onCreate()", Toast.LENGTH_LONG).show();
if (isConnected()) {
fixSocket = MyUDPClient.getApplicationClient(this);
} else {
// TODO: This is a crude check. Should probably be rolled into UDPClient class directly.
Log.w(TAG, "Network unavailable! Stopping positioning service.");
stopSelf();
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onStart()", Toast.LENGTH_LONG).show();
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
for (String provider : ((LocationManager) getSystemService(LOCATION_SERVICE)).getAllProviders()) {
if (!provider.equals("passive")) {
MyADB.log("Registering for updates with " + provider);
((LocationManager) getSystemService(LOCATION_SERVICE)).requestLocationUpdates(provider, 0, 0, this);
}
}
}
public void onStop() {
unregisterReceiver(batteryReceiver);
((LocationManager) getSystemService(LOCATION_SERVICE)).removeUpdates(this);
}
#Override
public void onDestroy() {
unregisterReceiver(batteryReceiver);
((LocationManager) getSystemService(LOCATION_SERVICE)).removeUpdates(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startid) {
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onStartCommand()", Toast.LENGTH_LONG).show();
onStart(intent, startid);
return Service.START_REDELIVER_INTENT;
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MyGeoloqiPositioning.this, "MyGeoloqiPositiong in onLocationChanged()", Toast.LENGTH_LONG).show();
#SuppressWarnings("unchecked")
MyFix lqLocation = new MyFix(location, new Pair<String, String>("battery", "" + batteryLevel));
if (isConnected()) {
fixSocket.pushFix(lqLocation);
} else {
// TODO: This is a crude check. Should probably be rolled into UDPClient class directly.
Log.w(TAG, "Network unavailable, failed to push location fix!");
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
batteryLevel = intent.getIntExtra("level", 0);
}
};
/** Determine if the network is connected and available. */
private boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
return (activeNetwork != null && activeNetwork.isConnected());
}
}
I tried inserting a breakpoint in MyGeoloqiPositioning, but nothing ever comes of it. I also put various Toast() calls, but still no dice. My GeoloqiPositioning.java is never called. What am I doing wrong?
EDIT:
Here is the new code from the manifest file:
<service
android:name="com.manhunttwopointoh.MyGeoloqiPositioning"
android:enabled="true"
android:exported="false"
android:process=":lqRemote" >
<intent-filter>
<action android:name="com.manhunttwopointoh.MyGeoloqiPositioning" />
</intent-filter>
</service>
I tried adding the intent-filter tags, but still nothing. I also have nothing registering on the logs. Here is the code (commented out stopService()):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geoloqi);
Intent mPositioningIntent = new Intent(this, MyGeoloqiPositioning.class);
//stopService(mPositioningIntent);
startService(mPositioningIntent);
Toast.makeText(PreyGeoloqi.this, "testing mPositioningIntent: " + mPositioningIntent.toString(), Toast.LENGTH_LONG).show();
}
I still get nothing. Do I need to explicitly call methods in MyPreyGeoloqi.java? I am fairly confused...

Try adding an intent filter your service definition in the AndroidManifest:
<!-- snippet from Android Manifest file -->
<service android:name="com.manhunttwopointoh.MyGeoloqiPositioning" android:enabled="true" android:process=":lqRemote" >
<intent-filter>
<action android:name="com.manhunttwopointoh.MyGeoloqiPositioning" />
</intent-filter>
</service>
This allows your service to receive the intent sent from your Activity.

Related

Cannot able run Bluetooth Scanning in Foreground service more than 10 - 15 secs even though Notification is provided

I have used Service to keep my scan for android mobiles even when the app is closed. I used Broadcast receiver to restart my service when killed. It restarts the scanning and it works only for some 15 seconds and then stops
When i click button1 in {MainActivity} I started the service and have called startdiscovery() in startCommand method in {ExampleService}
Please Help me in running the app in background
MainActivity.java
import android.Manifest;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.bluetooth.le.ScanResult;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
ListView scanListView;
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
static BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
FirebaseFirestore db = FirebaseFirestore.getInstance();
static int count=0;
ScanResult sc;
String Uuid;
Date currentTime;
private LocationSettingsRequest.Builder builder;
private final int REQUEST_CHECK_CODE=8989;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
LocationManager locationm;
String provider;
Button button1;
BluetoothAdapter bluetoothAdapter;
Intent btEnablingIntent;
int requestCodeForEnable;
Button button;
Button scanButton1;
RegisterActivity registerActivity=new RegisterActivity();
String email ;
String phone ;
///
Intent discoverableIntenet = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
Intent mServiceIntent;
private ExampleService mYourService;
Context ctx;
public Context getCtx() {
return ctx;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentTime = Calendar.getInstance().getTime();
setContentView(R.layout.activity_main);
checkLocationPermission();
btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
requestCodeForEnable=1;
discoverableIntenet.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(discoverableIntenet);
button=(Button) findViewById(R.id.button4);
Intent intent = new Intent(MainActivity.this,ble.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,ble.class);
MainActivity.this.startActivity(intent);
}
});
button=(Button) findViewById(R.id.button6);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
open(view);
}
});
button=(Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pdfs(view);
}
});
button=(Button) findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myths(view);
}
});
button1=(Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
analytics(view);
}
});
scanListView = (ListView) findViewById(R.id.scannedListView);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
scanButton1=(Button) findViewById(R.id.Button1);
scanButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("disc","discoveeery!");
Log.i("hiiiiiii", String.valueOf(myAdapter.isDiscovering()));
Intent serviceIntent = new Intent(MainActivity.this, ExampleService.class);
serviceIntent.putExtra("inputExtra", "hi");
// startService( serviceIntent);
mYourService = new ExampleService();
mServiceIntent = new Intent(MainActivity.this, mYourService.getClass());
if (!isMyServiceRunning(mYourService.getClass())) {
startService(mServiceIntent);
}
}
});
bluetoothOnMethod();
BluetoothFunctions();
}
public void BluetoothFunctions(){
Log.d("disc", "discovery!");
IntentFilter intentFilter;
intentFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(myreceiver, intentFilter);
intentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(myreceiver, intentFilter);
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, stringArrayList);
scanListView.setAdapter(arrayAdapter);
Uuid="02.020202.020.02";
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == requestCodeForEnable) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is enabled", Toast.LENGTH_LONG).show();
}
else if(resultCode==RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth enabling cancelled", Toast.LENGTH_LONG).show();
}
}
}
final BroadcastReceiver myreceiver = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName() == null) {
return;
}
String address = device.getName();
int N = 2;
float type = intent.getFloatExtra((BluetoothDevice.EXTRA_UUID),Float.MIN_VALUE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
String rssi_val = String.valueOf(rssi);
String data = device.getAddress() + " " + rssi_val;
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
stringArrayList.add(data);
if (rssi >= -50) {
v1.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
count++;
if (device.getAddress() != null) {
Firebasepush(device.getAddress(), rssi_val);
}
}
Log.i("lll", device.getAddress());
Log.i("lll", device.getName());
Log.i("+>>>>>>>>>>>>>", BluetoothDevice.EXTRA_UUID);
Log.i("lll", rssi_val);
arrayAdapter.notifyDataSetChanged();
// Toast.makeText(getApplicationContext()," TX power: " +sc.getTxPower() + "dBm", Toast.LENGTH_SHORT).show();
//startThread();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.v("ggggggggg", "Entered the Finished ");
myAdapter.startDiscovery();
}
}
};
public void Firebasepush(String uuid,String rrsi){
Map<String, Object> updateMap = new HashMap();
updateMap.put("RSSI", rrsi);
updateMap.put("time", currentTime);
Map<String, Object> countMap = new HashMap();
countMap.put("Count", count);
countMap.put("time", currentTime);
countMap.put("Name",registerActivity.NameString);
countMap.put("Email",registerActivity.EmailId);
countMap.put("Phone Number",registerActivity.PhoneNumber);
// Add a new document with a generated ID
db.collection("users").document(Uuid).collection("contacts").document(uuid)
.set(updateMap);
db.collection("users").document(Uuid).
set(countMap);
}
void bluetoothOnMethod() {
if(bluetoothAdapter==null){
Toast.makeText(getApplicationContext(), "Bluetooth does not support ",Toast.LENGTH_LONG).show();
}
else {
if(!bluetoothAdapter.isEnabled()){
startActivityForResult(btEnablingIntent,requestCodeForEnable);
}
}
}
public boolean checkLocationPermission() {
LocationRequest request = new LocationRequest()
.setFastestInterval(1500)
.setInterval(3000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder = new LocationSettingsRequest.Builder()
.addLocationRequest(request);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient( this).checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try{
task.getResult(ApiException.class);
}catch (ApiException e){
switch (e.getStatusCode())
{
case LocationSettingsStatusCodes
.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException= (ResolvableApiException) e;
resolvableApiException.startResolutionForResult(MainActivity.this,REQUEST_CHECK_CODE);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}catch (ClassCastException ex){
}break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
{ break;}
}
}
}
});
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
// locationm.requestLocationUpdates(provider, 400, 1,this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("Service status", "Running");
return true;
}
}
Log.i ("Service status", "Not running");
return false;
}
#Override
protected void onDestroy() {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
// Don't forget to unregister the ACTION_FOUND receiver.
// unregisterReceiver(myreceiver);
}
public void openservices(){
Intent intnt=new Intent(this ,Services.class);
startActivity(intnt);
}
public void open(View view)
{
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.hogist.com/#/"));
startActivity(browserIntent);
}
public void pdfs(View view)
{
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.mohfw.gov.in/pdf/Illustrativeguidelineupdate.pdf"));
startActivity(browserIntent);
}
public void myths(View view)
{
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.mohfw.gov.in/pdf/Illustrativeguidelineupdate.pdf"));
startActivity(browserIntent);
}
public void analytics(View view){
final Intent intent1 = new Intent(MainActivity.this, Analytics.class);
startActivity(intent1);
}
}
ExampleService.java
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import java.util.Timer;
import java.util.TimerTask;
public class ExampleService extends Service {
BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
MainActivity mainActivity=new MainActivity();
public int counter=0;
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// startTimer();
myAdapter.startDiscovery();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// stoptimertask();
myAdapter.cancelDiscovery();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}```
Restarter.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
public class Restarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast Listened", "Service tried to stop");
Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.i(Restarter.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startForegroundService(new Intent(context, ExampleService.class));
} else {
context.startService(new Intent(context, ExampleService.class));
}
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hogist_social_distancing">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:name=".App"
android:fullBackupContent="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=".Analytics"
android:screenOrientation="portrait" />
<activity
android:name=".Services"
android:screenOrientation="portrait" />
<activity
android:name=".Permissions"
android:screenOrientation="portrait" />
<activity
android:name=".MainActivity"
android:screenOrientation="portrait" />
<activity android:name=".RegisterActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OTPActivity" />
<activity android:name=".ble" />
<service
android:name=".ExampleService"
android:enabled="true" />
<receiver
android:name="Restarter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="restartservice" />
</intent-filter>
</receiver>
</application>
</manifest>```
Android strives to save the battery, so it's expected that your service is stopped, especially if it runs battery draining operations such as Bluetooth scans.
Also, bare in mind that starting from Android 7, an app cannot start the BLE scan more than 5 times per 30 seconds, as mentioned here. Other issues related to BLE scanning are listed here.
If you do want to run Bluetooth scans in the background, I suggest you use a JobIntentService, in which you start BLE scan for a few seconds.
JobIntentService is very similar to IntentService but with few benefits like holding a wake lock which prevents the CPU to go to sleep
Also, this type of service does not require displaying a notification to your user. For more info: https://developer.android.com/reference/androidx/core/app/JobIntentService
are you sure your bluetooth code can work well on activity (without service)?
you can not restart your service by call Broadcast when you service was killed, because when your service was killed by OS system, it will kill your application process so your broadcast will not work. When you call return START_STICKY; it means system will automatic restart your service when it have available resource

Android listen to Lock screen displayed

I want to do a method when lock screen displayed (not when unlocked or screen on, just when lock screen displayed).
i try with broadcast and services but they don't work after killing app.
Also In eclips LogCat i see a log like /WindowManager(473): Lock screen displayed! that genymotion produce .
maybe can be done with windowmanager..
Try something like the following:
KeyguardManager myKM = (KeyguardManager)
context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
// it is locked
}
else {
// it is not locked
}
This should allow you to determine the locked status of the device.
I found it.
using service and set it START_STICKY.
after killing service the service restart again.
it is my code :
android manifest :
<application
....
<service android:name=".UpdateService" />
</application>
service class :
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if ( !screenOn) {
Log.i("screenON", "Called");
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
Toast.makeText(getApplicationContext(), "Sleep",
Toast.LENGTH_LONG)
.show();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
receiver class :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
Log.i("screenLog", "screen off");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
Log.i("screenLog", "screen on");
}
}
}
in StartupActivity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context context = getApplicationContext();
Intent service = new Intent(context, UpdateService.class);
context.startService(service);
}

How to block call in Android 4.2

My Note :as I have already clarified in my initial post, I don't think it's a duplicate,
I already tried these method and it doesn't work for me,
The code below seems only work for 2.2, it requires MODIFY_PHONE_STATE which is not permitted after Android 2.2****
This is not duplicated questions since i have already looked many other post here and it doesn't work for me
I follow the solution from the link below:
block phone call
TelephonyManager tm = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
Class<?> c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
But the code give me exception when run on real device(which is Android 4.2)
java.lang.NoSuchMethodException: getITelephony
So, does it still possible use this solution on Android 4.2, if not,does there exist other solutions i can try?
Thanks a lot in advance
Create a file named ITelephony.aidl it should contain these data:
package com.android.internal.telephony;
interface ITelephony
{
boolean endCall();
void answerRingingCall();
void silenceRinger();
}
Create these folders under src
android > internal > telephony
Then Place the ITelephony.adl under telephony folder.
Copy this DeviceStateListener class and place it under any package on your project.
import android.content.Context;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import java.lang.reflect.Method;
public class DeviceStateListener extends PhoneStateListener {
private ITelephony telephonyService;
private Context context;
public DeviceStateListener(Context context) {
this.context = context;
initializeTelephonyService();
}
private void initializeTelephonyService() {
try {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
Class clase = Class.forName(telephonyManager.getClass().getName());
try{
Method method = clase.getDeclaredMethod("getITelephony");
}catch (NoSuchMethodException e){
e.printStackTrace();
}
method.setAccessible(true);
telephonyService = (ITelephony) method.invoke(telephonyManager);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCallStateChanged(int state, final String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
boolean isNumberIsBlocked=false;
// You can check here if incomingNumber string is under your blacklisted numbers
if (isNumberIsBlocked) {
try {
// This is the main code that block the incoming call.
telephonyService.endCall();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// You can run anything here lets say a notice to the user if a call is blocked
}
});
t.start();
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
}
}
}
Here is another important class "ServiceReceiver" place it also under any package of your project and resolve all possible imports.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class ServiceReciever extends BroadcastReceiver
{
private static TelephonyManager telephony;
private static DeviceStateListener phoneListener;
private static boolean firstTime=true;
public ServiceReciever(Context context)
{
telephony=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
phoneListener=new DeviceStateListener(context);
}
#Override
public void onReceive(Context context, Intent intent)
{
if(firstTime)
{
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
firstTime = false;
}
}
// You can use this in the future to stop the call blocker feature.
public void stopListening() {
telephony.listen(phoneListener, PhoneStateListener.LISTEN_NONE);
firstTime=true;
}
}
Copy this CallBlockerService class also and place it under any package of your project. It is an unkillable service that invokes the ServiceReceiver class.
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import com.katadigital.phone.callsmsblocker.callListener.ServiceReciever;
public class CallBlockerService extends Service {
public static final int notification_id = 111;
// ---------------------------------------
// Listening Services
// ---------------------------------------
private static ServiceReciever service;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
service = new ServiceReciever(getApplicationContext());
registerReceiver(service, new IntentFilter(
"android.intent.action.PHONE_STATE"));
System.out.println("Call blocker is running now");
}
#Override
public void onDestroy() {
service.stopListening();
unregisterReceiver(service);
service = null;
cancelStatusBarNotification();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void cancelStatusBarNotification() {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(notification_id);
}
}
Place this AfterBootReceiver class beside our CallBlockerService. Its job is to restart the blocker service when the phone starts from shutdown.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AfterBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent serviceLauncher = new Intent(context, CallBlockerService.class);
context.startService(serviceLauncher);
}
}
Lastly place this on your AndroidManifest under tag.
<receiver android:name="com.callblocker.services.AfterBootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="com.callblocker.services.CallBlockerService" >
</service>
Replace "com.callblocker.services" with the folder location of the CallBlockerService and your AfterBootReceiver
I have tested this code until Android 4.4 KitKat. I hope you can follow the steps and it helps you with your problem.

My android location service killed when app switched to background

Please apologize me if my question is repeated or simple. Struggling in this issue for a long time.
I need to track user's location even when my app is switched to background. On surfing I found that the location processor code can be written as a service, so that the service will not be killed and we can get the user's location (in both status - app in foreground and when app runs in background).
When my app is in foreground, I was able to track user's location continuously. However, when I switched the app to background, I feel my location service dies and I was not able to track user's location. Please find my code below:
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testmylocation"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<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>
MainActivity.java:
package com.example.testmylocation;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.Window;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyService.java:
package com.example.testmylocation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class MyService extends Service
{
private static final String TAG = "TestMyLocation";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
long itsBatchId = 0;
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Thread aThread = new Thread(new Runnable() {
#Override
public void run() {
sendLocationValues(location);
}
});
aThread.start();
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
private void sendLocationValues(Location theLocation)
{
//A web service will be called and the user's current location will be stored in server
}
LocationListener[] mLocationListeners = new LocationListener[]
{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
initializeLocationManager();
itsLocationHandler.sendEmptyMessage(1);
}
private Handler itsLocationHandler = new Handler()
{
#Override
public void handleMessage(Message theMessage)
{
if(theMessage.what == 1)
{
try
{
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]);
}
catch (java.lang.SecurityException ex)
{
Log.i(TAG, "fail to request location update, ignore", ex);
}
catch (IllegalArgumentException ex)
{
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
}
}
};
#Override
public void onDestroy()
{
super.onDestroy();
}
private void initializeLocationManager()
{
if (mLocationManager == null)
{
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
Can anyone please correct what I am doing wrong.
Thank you.
Since Android 4.0, the OS has gotten much more agressive about killing off unnecessary processes. If you need to track the user's location even when your app is in the background, then you need to declare your service as a foreground service. This raises the priority of your service so that Android is unlikely to kill it unless it really needs the resources. See Running a service in the foreground for details about how to do this.
location processor code can be written as a service, so that the service will not be killed
There is nothing can guarntee that the service will never be killed, however you can increase the likelihood that your service will continue running by obtaining WakeLock and start it as Foreground service
I would recommend you check few open source projects such as Open GPS Tracker and Traceper

Service methods not working in android

I just created a service as shown below :
package com.example.timepass;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class alarm extends Service{
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Entered in service", Toast.LENGTH_SHORT).show();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
return 1;
// Log.i("YourService", "Yes this works.");
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Changed", Toast.LENGTH_SHORT).show();
return null;
}
}
Now when I startservice from mainactivity by the following command:
Intent myIntent = new Intent("com.example.timepass.ALARM");
MainActivity.this.startService(myIntent);
By doing this there is no error, but no TOAST of Service class are dipslayed
My manifest is :
<service class=".alarm" android:name=".alarm" android:enabled="true">
<intent-filter>
<action android:value="com.example.timepass.ALARM"
android:name=".alarm" />
</intent-filter>
</service>
Please guide me!!!
Probably you don't have the service in your manifest, or it does not have an that matches your action. Examining LogCat should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, alarm.class));

Categories

Resources