I'm writing this service but I can't see the log strings when I launch the app.
if I put a Log.i in the method startBeaconDetecting I can see it but after the onCreate() method doesn't start.
Why onCreate doesn't run?
public class ProximityBeacon extends Service
{
private String server;
private String ID;
public ProximityBeacon(String server)
{
this.server=server;
//TODO indirizzo del server
}
public void startBeaconDetecting(String ID, Intent intent, Context context)
{
this.ID=ID;
context.startService(intent);
}
public void stopBeaconDetecting()
{
stopSelf();
onDestroy();
}
public void onCreate()
{
super.onCreate();
Log.i(TAG, "Oncreate");
}
public int onStartCommand(Intent intent, int flag, int startId)
{
Log.i(TAG, "onStartCommand");
return Service.START_STICKY;
}
}
Change your Service class to this:
public class ProximityBeacon extends Service
{
private static final String TAG = "TAG";
private String server;
private String ID;
public ProximityBeacon() {
}
public ProximityBeacon(String server)
{
this.server=server;
//TODO indirizzo del server
}
public void startBeaconDetecting(String ID, Intent intent, Context context)
{
this.ID=ID;
context.startService(intent);
}
public void stopBeaconDetecting()
{
stopSelf();
onDestroy();
}
public void onCreate()
{
super.onCreate();
Log.i(TAG, "ProximityBeacon Oncreate");
}
public int onStartCommand(Intent intent, int flag, int startId)
{
Log.i(TAG, "ProximityBeaconon StartCommand");
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and then call it using this:
new ProximityBeacon("").startBeaconDetecting("" ,new Intent(HomeActivity.this, ProximityBeacon.class) ,mContext) ;
then add it in manifest.xml like this :
<service android:name=".services.ProximityBeacon" />
Output : 19:25:11.873 23002-23002/com.sample.service I/TAG: ProximityBeaconon StartCommand
after startService(service); will run onStartCommand, not onCreate
Related
I have created a service. When I start it from MainActivity its started but when I click on button to stop it it's doesn't stop. It is working fine in lower version devices but only issue found in Android 10 or higher versions.
public void startServices() {
Intent intent = new Intent(getApplicationContext(), PerformTaskService.class);
startService(intent);
}
public void stopServices() {
stopService(new Intent(getApplicationContext(), PerformTaskService.class));
}
PerformTaskService.java
public class PerformTaskService extends Service {
String TAG = "ServiceStatus";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
int id;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.id = startId;
Log.e(TAG, "onStartCommand: "+startId );
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
stopSelfResult(id);
stopSelf(id);
new StatusBarService().onDestroy();
stopSelf();
super.onDestroy();
}
}
StatusBarService.java
public class StatusBarService extends AccessibilityService {
int id;
#Override
public ComponentName startForegroundService(Intent service) {
return super.startForegroundService(service);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.id = startId;
return START_NOT_STICKY;
}
#SuppressLint({"InflateParams", "InlinedApi"})
#Override
public void onCreate() {
super.onCreate();
View mFloatingView =
LayoutInflater.from(this).inflate(R.layout.layout_floating_widget,
null);
thumbView =
LayoutInflater.from(this).inflate(R.layout.layout_seekbar_thumb,
null, false);
deviceManger = ((DevicePolicyManager)
getSystemService(Context.DEVICE_POLICY_SERVICE));
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
#Override
public void onInterrupt() {
}
public void deviceadminCheck() {
Intent intent = new
Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onDestroy() {
stopSelf();
stopSelf(id);
stopSelfResult(id);
super.onDestroy();
}
}
So, kindly let me know if you have any proper solution or Idea about this issue. how to stop service
I made a simple example in order to test an un-killable service. I'm trying to restart as soon as it is killed by OS.
Everything works well. But, I found that the service was sometimes killed by OS frequently, and re-started again in OS over 6.0. Sometimes, onStartCommand is called in 30 seconds after starting the service. I don't know why.
OS under 6.0 works perfectly well.
My code is simple.
public class DataCollectorService extends Service {
public static BroadcastReceiver broadcastReceiver;
private Intent intent_data_processor;
private PendingIntent sender_data_processor;
private AlarmManager alarmMgr;
private LocalBroadcastManager a_manager;
private String TAG = "DataCollectorService";
private DatabaseReference mFirebaseDatabaseReference;
private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
public DataCollectorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public DataCollectorService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
release();
}
#Override
protected void finalize() throws Throwable {
super.finalize();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.e("TAG", "START");
Log.e("TAG", "DataCollectorService onStartCommand");
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public boolean onUnbind(Intent arg0) {
return true;
}
#Override
public void onRebind(Intent arg0) {
}
And then I also set up the service like following in Manifest.
android:enabled="true"
android:exported="false"
What is the reason that the service is restarted within a few seconds after the starting?
I have simple app for testing android:process attribute of service. So my service looks like this:
public class MyService extends IntentService {
static final String TAG = "MyService";
public MyService() {
super("MyService");
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"onCreate()");
}
#Override
protected void onHandleIntent(Intent intent) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
doJob();
return START_STICKY;
}
private void doJob() {
new Thread(new Runnable() {
#Override
public void run() {
Log.i(TAG,"job started");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG,"job stopped");
stopSelf();
}
}).start();
}
}
I'm trying to start service from the activity as follows:
findViewById(R.id.startServiceBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(getApplicationContext(),MyService.class));
}
});
All works fine. Now i'm adding android:process=":service" attribute to service declaration in the manifest. And after that service doesnt't start. So why so and what should i change for start service in separate process?
I think you have to do this task i.e dowork() method call in onHandleIntent(). Because your service class extending Intent service instead of Service.
public class MyService extends IntentService {
static final String TAG = "MyService";
public MyService() {
super("MyService");
}
#Override
protected void onHandleIntent(Intent intent) {
doJob();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
}
private void doJob() {
new Thread(new Runnable() {
#Override
public void run() {
Log.i(TAG,"job started");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG,"job stopped");
stopSelf();
}
}).start();
}
}
oh sorry it was silly mistake - i have to select new process in android monitor tab) thanks to all
I have the following abstract class:
public abstract class AbstractService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This class is extended by two other classes:
public abstract class AbstractMessengerService extends AbstractService {
static final int MSG_REGISTER_CLIENT = 9991;
static final int MSG_UNREGISTER_CLIENT = 9992;
ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.
private class IncomingHandler extends Handler { // Handler of incoming messages from clients.
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
Log.i("MyService", "Client registered: " + msg.replyTo);
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
Log.i("MyService", "Client un-registered: "+msg.replyTo);
mClients.remove(msg.replyTo);
break;
default:
//super.handleMessage(msg);
onReceiveMessage(msg);
}
}
}
#Override
public void onCreate() {
super.onCreate();
onStartService();
Log.i("MyService", "Service Started.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService", "Received start id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
#Override
public void onDestroy() {
super.onDestroy();
onStopService();
Log.i("MyService", "Service Stopped.");
}
protected void send(Message msg) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
Log.i("MyService", "Sending message to clients: "+msg);
mClients.get(i).send(msg);
}
catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
Log.e("MyService", "Client is dead. Removing from list: "+i);
mClients.remove(i);
}
}
}
public abstract void onStartService();
public abstract void onStopService();
public abstract void onReceiveMessage(Message msg);
}
And:
public abstract class AbstractAIDLService extends AbstractService {
private Handler handler;
ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid(){
return android.os.Process.myPid();
}
#Override
public void setActivityColor(String color, long startTime) throws RemoteException {
long elpsedTime = (System.nanoTime() - startTime) / (1000 * 1000);
showElpesedTime(String.valueOf(elpsedTime));
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
private void showElpesedTime(final String time)
{
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(AbstractAIDLService.this, "Time passed reaching the server: "+time+"ms", Toast.LENGTH_SHORT);
toast.show();
}
});
}
#Override
public void onCreate() {
super.onCreate();
onStartService();
Log.i("MyService", "Service Started.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService", "Received start id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onDestroy() {
super.onDestroy();
onStopService();
Log.i("MyService", "Service Stopped.");
}
public abstract void onStartService();
public abstract void onStopService();
public abstract void onReceiveMessage(Message msg);
}
Now I created a ServiceManager class which is a factory class that I want to create concrete version of those class and passed them to this manager class. I have a constructor in this ServiceManager:
public class ServiceManager {
private static final String TAG = ServiceManager.class.getSimpleName();
private Class<? extends AbstractService> mServiceClass;
public ServiceManager(Context context, ServiceType type, Class<? extends AbstractService> serviceClass, Handler incomingHandler) {
this.mActivity = context;
this.mIncomingHandler = incomingHandler;
if (type.equals(ServiceType.AIDL)) {
this.mServiceClass = (AbstractAIDLService) serviceClass;
} else if (type.equals(ServiceType.MESSENGER)) {
this.mServiceClass = (AbstractMessengerService) serviceClass;
}
if (isRunning()) {
doBindService();
}
}
But for some reason, those lines: this.mServiceClass = (AbstractAIDLService) serviceClass;, this.mServiceClass = (AbstractMessengerService) serviceClass; give me a casting problem. How can this be done?
I think in your ServiceManager you cannot assign a AbstractAIDLService or AbstractMessengerService to Class<? extends AbstractService> mServiceClass because they are different classes and Class is not the father class of the other two.
I don't know what are you trying to do but this should work:
public class ServiceManager {
private static final String TAG = ServiceManager.class.getSimpleName();
private AbstractService mServiceClass;
public ServiceManager(Context context, ServiceType type, AbstractService serviceClass, Handler incomingHandler) {
this.mActivity = context;
this.mIncomingHandler = incomingHandler;
this.mServiceClass = serviceClass;
if (isRunning()) {
doBindService();
}
}
And save the ServiceType in other variable.
My problem is that I think my service runs multiple times. The service is controlled by a switch calling a method that starts and stops the service. I have a broadcast listener inside my service and the receiver logs whenever it receives a broadcast. at first switch on, it logs two times. After switch off and on, it logs four times.
public class Service1 extends Service implements DetectionListener {
private static final String TAG = "ListenerService";
private final broadcastReceiver1 receiver = new broadcastReceiver1();
public HashMap<String, String> hashMapData;
private ARSonicManager arSonicManager;
public ListenerService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.digify.almostrealsonic.broadcast_intent");
registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null != intent) {
try {
hashMapData = (HashMap<String, String>) intent.getSerializableExtra("hashMapData");
// Do something with hashMapData
} catch (Exception e) {
Log.i("onStartCommand", e.toString());
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onMarkerDetected(String markerKey) {
Intent intent = new Intent();
intent.putExtra("hashMapData", hashMapData);
intent.setAction("com.broadcastReceiver1_intent");
sendBroadcast(intent);
}
public static class broadcastReceiver1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String hashMapData = intent.getStringExtra("hashMapData");
Log.i("receiver", "Got message: " + hashMapData);
}
}
}