I've created a geo-location app that collects location information of the device and compares it to a pre-defined lat/long coordinates to perform certain actions when they match.
Currently I have an activity page where the users can enter the coordinates as well as other parameters such as radius and interval for polling. Also, the app starts only when the user starts it.
I wish to convert it into a service that does the following
runs in the background
parameters are read from a configuration file (this part is already done) hence no need for any main activity (no UI)
starts up automatically (probably need an android.intent.action.BOOT_COMPLETED BroadcastReceiver)
How do I do this?
Thanks.
You have to create a service for your application, like this:
ExampleService.java:
public class ExampleService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.d(TAG, "onStart()===>In");
// Write your application logical code here
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
BootCompleteReceiver.java
public class BootCompleteReceiver extends BroadcastReceiver {
private static final String TAG = "[BootCompleteReceiver]";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Boot complete", Toast.LENGTH_LONG).show();
Log.d(TAG, "Boot complete");
// Start the ExampleService
Intent service = new Intent(context, ExampleService.class);
context.startService(service);
}
}
In Android Manifest:
<!-- Server as a service -->
<service
android:name="com.example.ExampleService"
android:enabled="true" >
</service>
<!-- Boot complete receiver -->
<receiver
android:name="com.example.BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You also have to create a activity to start the service manually and awake the service from the activity.
Related
I want to implement this scenario for my application. I want to schedule my service to start when the phone boots, and whenever another application calls my service I want my service to start a certain activity within the project.
So in order to be clear. I want to create a project which contains a service which runs whenever the phone boots, and is dormant, listening for a call from a third party application. And whenever that call is received this service calls an Activity (from the same project, not third party)
How can I configure my manifest file in order to achieve this?
I have also come across this suggestion but my scenario is pretty different.
Thank you very much in advance
**Define Service in manifest and Create the BroadcastReciever with boot complete permission and listen the intent.If boot completed start the service.**
public class MyService extends Service {
Context context = this;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Intent activity = new Intent(context, MyActivity.class);
activity.putExtra("Message", "fromService");
activity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(activity );
} catch (Exception e) {
MyLog.printException(e);
}
return super.onStartCommand(intent, flags, startId);
}
}
By creating a BroadcastReceiver you can perform the service startup.
public class StartupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(context, ShowActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
and in the manifest
<receiver
android:name=".StartupReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
This allows you to run an Activity, you can then start a Foreground Service from that activity. I just set this example because I have it ready, you can adapt it to run a service as you like.
I need to have a service in background working on Android.
I made this service:
public class ServizioBackgrounds extends IntentService {
public static int DEFAULT_PORT = 35500;
private static int BUF_SIZE = 11;
private static ....
private static ....
public ServizioBackgrounds() {
super("ServizioBackground");
}
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("##### Servizio Attivato #####");
super.onStart(intent, startId); // If I don't use, the onHandleIntent method ins't call
return START_STICKY;
}
public void onDestroy(){
System.out.println("### Servizio Terminato ###");
Intent startService = new Intent("com.perseusgalaxia.interphone_citofono"); // Try.. But this method is never called
startService.putExtra("AccendiServ", "AccendiServ");
sendBroadcast(startService);
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("##### SIAMO DENTRO #####");
DatagramSocket socketAttesa = null;
System.out.println("*** IL SERVIZIO E' ATTIVO ***");
while(true){
...
}
}
}
Then I have this BroadcasterReceiver:
public class BootCompletedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("*** Broadcast Ricevuto ***");
context.startService(new Intent(context,ServizioBackgrounds.class));
}
}
And this is the manifest:
<service android:name=".ServizioBackground"
/>
<receiver android:name=".BootCompletedReceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="com.perseusgalaxia.interphone_citofono" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This is the part where I start the service for the first time:
Intent startService = new Intent("com.perseusgalaxia.interphone_citofono");
startService.putExtra("AccendiServ", "AccendiServ");
sendBroadcast(startService);
I call the service in this way just for try.
The problem is that if I start from the app activity the service it start and works fine, but when I close the app the service is close too.
The amazing thing is that if I restart the smartphone the service start in background (without any activity shown etc.) and it works fine. Then (after reboot) if I start the app and close them the service come be closed!
Sorry for my english.
Thank's for answer.
To run your service in the background you need to call startForeground from your service.
Here's an example:
int serviceId = 101;
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setContentTitle("Working...")
.setContentText("I'm working!")
.setSmallIcon(R.mipmap.ic_launcher);
startForeground(serviceId, b.build());
Note that if your service runs in the background you must show a notification, so the user is notified about your work.
My target Android is 4.1.2. I created an simple android service which will show Toast on boot. But this application should not have any GUI. I was success running this service only from an activity which show GUI on start.
public class MyServices extends Service {
private MediaRecorder recorder = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int StartId)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
}
You can start this service from RebootReceiver but As of Android 3.0 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events.
Reboot Receiver -> Android BroadcastReceiver on startup - keep running when Activity is in Background
First you have to create a receiver:
public class BootCompletedReceiver extends BroadcastReceiver {
final static String TAG = "BootCompletedReceiver";
#Override
public void onReceive(Context context, Intent arg1) {
Log.w(TAG, "starting service...");
context.startService(new Intent(context, MyServices.class));
}
}
Then add permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and register intent receiver:
<receiver android:name=".BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
After this is done, your application (Application class) will run along with services, but no Activities, don't put your application on SD card (APP2SD or something like that), because it has to reside in the main memory to be available right after the boot is completed.
I am new to android, I have created intent's like this -
<receiver android:name=".IncommigCallListener" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<receiver android:name=".OutgoingCallReciever" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
Now i created a service like this -
<service
android:name=".CallLogger"
android:exported="false"/>
Class CallLogger
public class CallLogger extends IntentService {
public CallLogger(String name) {
super(name);
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("service started");
}
}
I don't want to have any activity in my application, i just want to start the service so that it can work in background and receive PHONE_STATE and NEW_OUTGOING_CALL intent.
When i start this application, it doesn't log anything on PHONE_STATE or NEW_OUTGOING_CALL intent.
How can start service in background without using any activity ?
Edit :
public class OutgoingCallReciever extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
}
and
public class IncommigCallListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
String incommingCallNumber = incomingNumber;
System.out.println("incomming call : " + incomingNumber);
break;
}
}
}
Just start service in your BroadcastReceiver's onReceive method. As you are registering BroadcastReceiver in AndroidManifist, It will always listen for Broadcasts even if application is not running (OS will run it for you).
Example
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
EDIT
To start a service on Boot completed you can do something like this.
1) Add permission to your Manifist :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2) Register your Broadcast Receiver with BOOT COMPLETE action.
<receiver android:name="com.example.BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
3) In BootBroadcastReceiver.java:
public class BootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent );
}
}
You should be able to do something like this in your receiver.
public class OutgoingCallReciever extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Intent service = new Intent(context, CallLogger.class);
context.startService(service);
}
}
You need to create an intent and call startService() on it to "launch" the service.
Also for what it's worth you should get out of the habbit of System.out.println use Log.d(tag,msg) to print debugging information to the logcat. You can switch the d to other letters if you want to print in different channels.
Why nothing gets printed is only due to the problem that System.out.println does not work in Android! Where do you think the background process will "print" this thing?
You need to change that to Log.d(tag, msg) and then check your logcat to see the output! Otherwise I guess your code might be running properly.
Hi i have developed an service application using activity and that works great in 2.2 and 2.3 android version and it starts on boot and runs my app for once in 30 mins and sending location to server but in 4.0 the app is not running on services on boot can anybody say me why?
my code:
BroadcastReceiver.java:
public class autostart extends BroadcastReceiver {
public void onReceive(Context arg0, Intent arg1) {
if ("android.intent.action.BOOT_COMPLETED".equals(arg1.getAction())) {
Intent intent = new Intent(arg0, gps_back_process.class);
arg0.startService(intent);
Log.i("Autostart", "started");
}
}
}
service.java:
public class gps_back_process extends Service
{
private static final String TAG = "MyService";
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("Testing", "Service got created");
Toast.makeText(this, "gps_back_process,onCreate();", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "gps_back_process.onCreate();", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<receiver android:name=".autostart" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity" >
</activity>
<service
android:name=".gps_back_process"
android:enabled="true" />
</application>
thank you.
Once the user runs the app for the first time (and does not force stop it), everything behaves as before — a reboot will cause BOOT_COMPLETED broadcasts to be received and so on. However, if the user installs the app, until and unless they run the app manually, no broadcasts will be received. And if the user force-stops the app, until and unless they run the app manually, no broadcasts will be received.
Check this for more detail.
This happens because from Android 3.1+ you Service will not run on Boot unless you start(launch) your Application atleast once after installation. So, when you install your Application and restart the device prior of launching the Applications MainActivity your BroadCastReceiver won't be fired. For that you have to launch your MainActivity once and then restart the device. That works!
For reference you can check my question here.
You should add add android.permission.RECEIVE_BOOT_COMPLETED,
If you don't have this permission your app won't receive the boot completed intent.