How to creat a background service for android developing - android

Hi I am new to android and it is also my first time I am going work with service which will work in the background.
I mean I want to build a voice commanding application and I want it to listen the user's command even when it is closed. And I want to start my service at the time of pressing the 'Back' button by any user.
I will be so grateful for your great help.

Try this:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class Startappservice extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.enwaye_connect.MainActivity");
startActivity( LaunchIntent );
}
To start service on clicking back button:
Intent start= new Intent(this, Startappservice .class);
startService(start);
Add in your manifest:
<service android:name="your_package_name.Startappservice" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="our_package_name.Startappservice" />
</intent-filter>
</service>

You have to use the Service class. Create a class that derives from it and then you can add your methods to the service.
public class MyService extends Service {
// This is used to establish a communication with the service.
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
// Called when the service is created
#Override
public void onCreate() {
// YOUR CODE
}
// Called when the service is started
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// YOUR CODE
return START_STICKY;
}
// called when the service instance is destroyed
#Override
public void onDestroy() {
// YOUR CODE
}
// Returns the binder which is used for communication with the service.
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
To start the service use:
Intent start= new Intent(this, MyService.class);
startService(start);

Related

How to keep a Service alive?

How Whatsapp service keep working in background in huawei phones ?
I removed whatsapp of protected apps but Whatsapp service not closed in screen
off time.
I'm writing critical app that need to run every time but my service killed in screen off.
I want to write service like Whatsapp or AirDroid service
anyone can explain about that ?
I mean how to write service that specially not close by screen off in HUAWEI phones
This is my service code
AppLifeService
public class AppLifeService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startForeground(5, AppLifeReciever.createNotification(this));
return START_STICKY;
}
#Override
public void onDestroy() {
//startService(new Intent(this, AppLifeService.class)); Updated : not need
super.onDestroy();
}
}
You need to create a Service to "reopen" BroadcastService automatically when it's closed.
For example:
BroadcastService
public class MyBroadcastService extends BroadcastReceiver
{
#Override
public void onReceive(final Context context, Intent intent)
{
//do something
}
}
Service to "reopen" automatically
public class MyService extends Service
{
#Override
public void onCreate()
{
// Handler will get associated with the current thread,
// which is the main thread.
super.onCreate();
ctx = this;
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i(TAG, "onStartCommand");
//Toast.makeText(this, "onStartCommand", Toast.LENGTH_LONG).show();
return START_STICKY;
}
//launch when its closed
#Override
public void onDestroy()
{
super.onDestroy();
sendBroadcast(new Intent("YouWillNeverKillMe"));
Toast.makeText(this, "YouWillNeverKillMe TOAST!!", Toast.LENGTH_LONG).show();
}
}
Declare on your AndroidManifest.XML
<receiver android:name=".BroadcastServicesBackground.MyBroadcastService">
<intent-filter>
<!--That name (YouWillNeverKillMe) you wrote on Myservice-->
<action android:name="YouWillNeverKillMe"/>
<data android:scheme="package"/>
</intent-filter>
<intent-filter>
<!--To launch on device boot-->
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".Services.MyService"/>
Service with START_STICKY in retrun onStartCommand() will start again automatically you dont need to start it again in onDestroy()
#Override
public void onDestroy() {
// startService(new Intent(this, AppLifeService.class));
super.onDestroy();
}
#Sohail Zahid Answer tells you a way to repeatedly start a service again and again when stopped. But in order to keep a service alive like playing a song in a background.
The best Approach I found is
startForeground(int, Notification)
where int value must be unique for every notification
You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section. In this way the app will keep alive in background without any interuption.

Service is NOT running always even after I have used START_STICKY

Issues
Service is NOT running always even after I have used START_STICKY.
Sometimes I dont get any Toast Action for Outgoing call, is that mean service stops after some time ?
My Requirment
Application shows a Toast whenever user makes a outgoing call from the phone. For this I am using a BroadcastReceiver to tap the call action and a service (to run Receiver always). once I start this activity, it starts showing toast when a outgoing call get initiated ..but not Always.
Below is the complete code -
MainActivity.class
public class MainActivity extends Activity
{
CallNotifierService m_service;
boolean isBound = false;
private ServiceConnection m_serviceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName className, IBinder service)
{
m_service = ((CallNotifierService.MyBinder)service).getService();
Toast.makeText(MainActivity.this, "Service Connected", Toast.LENGTH_LONG).show();
isBound = true;
Intent intent = new Intent(MainActivity.this, CallNotifierService.class);
startService(intent);
}
#Override
public void onServiceDisconnected(ComponentName className)
{
m_service = null;
isBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, CallNotifierService.class);
bindService(intent, m_serviceConnection, Context.BIND_AUTO_CREATE);
}
.
.
.
}
CallNotifierService.class
public class CallNotifierService extends Service
{
private final IBinder myBinder = new MyBinder();
private static final String ACTION_OUTGOING_CALL = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
#Override
public IBinder onBind(Intent arg0)
{
return myBinder;
}
#Override
public void onDestroy()
{
Log.d("service", "destroy");
this.unregisterReceiver(this.br_call);
Toast.makeText(CallNotifierService.this, "Receiver Un-Registered", Toast.LENGTH_LONG).show();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUTGOING_CALL);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
Toast.makeText(CallNotifierService.this, "onStartCommand Called", Toast.LENGTH_LONG).show();
return START_STICKY;
}
public class MyBinder extends Binder
{
CallNotifierService getService()
{
return CallNotifierService.this;
}
}
public class CallBr extends BroadcastReceiver
{
public CallBr() {}
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Action:"+intent.getAction(), Toast.LENGTH_LONG).show();
}
}
}
You are getting the wrong approach here, by mixing a simple idea (that would work if done correctly) with more complicated ideas (that cannot work).
Keep in mind: services are not "always running" components, even when using START_STICKY.
The Android system will not hesitate to kill your service if it needs memory somewhere else. START_STICKY only means that the Android system will re-start your service when it can, calling onStartCommand as specified in the documentation.
If you need a service to really stick around, then you must use a foreground service. But it will have consequences on the UI (annoying notification icon always showing), and battery life, and you do not need this here.
Now here is the magic trick: your app does not need to be running for your BroadcastReceiver to work. All you need to do is to register it in your AndroidManifest.xml with the correct intent-filter:
<receiver android:name=".broadcastreceivers.CallBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
(also make sure your app has the required permissions, namely PROCESS_OUTGOING_CALLS).
Then all you need in code is:
public class CallBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_LONG).show();
}
}
No activity (except to ask for the PROCESS_OUTGOING_CALLS permission on Android 6+), no service, nothing. Simple and battery-efficient !
The service does get re-created, not not re-started.
If you override the onCreate and do a Log.d or a Toast, you will see that it gets called after your app is destroyed.
So the trick to keep it running after it is recreated is to do your code on the onCreate method and use the onStartCommand just to return START_STICKY.

Android Service Running as a separate process

I have a service Class in android. Is it be possible for a Service to run as a separate process than an application just for receiving SMS and enqueue them in a queue after that an application reads SMS from this Queue.
Is it possible to launch a separate service?
I have tag the source code of SmsService class below
public class SmsService extends Service {
private SMSReceiver mSMSreceiver;
private IntentFilter mIntentFilter;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public SmsService(){
/*dba = new DataBaseAdapter(this);*/
mSMSreceiver = new SMSReceiver();
}
#Override
public void onCreate(){
super.onCreate();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(ConstantClass.SMS_RECEIVED);
registerReceiver(mSMSreceiver,mIntentFilter);
}
#Override
public int onStartCommand(Intent intent , int flags, int type){
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
//unregisterReceiver(mSMSreceiver);
}
To enroll your service in a different process, you need to define android:process attribute when defining your service in AndroidManifest.xml
For example:
<service android:process=":kaushik" />
This will run your service in a new process called kaushik.

run app in background without activity alerts user when Contact or sms is deleted

i want to make my app to be run in background and listens for
contact,sms deletion events.
for that i created a service in my app but i dnt how to start without activity
my code is like this
public class DeleteService extends Service {
ContentResolver cr;
MyContentObserver observer=new MyContentObserver();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
#Override
public void onCreate() {
cpath=ContactsContract.Contacts.CONTENT_URI;
// some action
}
#Override
public void onDestroy() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Launch a background thread to do processing.
super.onStartCommand(intent, flags, startId);
cpath=ContactsContract.Contacts.CONTENT_URI;
cr=getContentResolver();
cur=cr.query(cpath, null, null, null, null);
this.getApplicationContext().getContentResolver().registerContentObserver(cpath, true, observer);
return Service.START_STICKY;
}
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
nfm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int NOTIFICATION_ID = 1;
Intent intent1 = new Intent();
PendingIntent pi = PendingIntent.getActivity(DeleteService.this, 1, intent1, 0);
nf=new Notification(R.drawable.ic_launcher,"Contact Database changed",System.currentTimeMillis());
nf.setLatestEventInfo(getApplicationContext(), "Delete Event", "contact name", pi);
nf.flags = nf.flags |
Notification.FLAG_ONGOING_EVENT;
}
#Override
public boolean deliverSelfNotifications()
{
super.deliverSelfNotifications();
return true;
}
}
public class LocalBinder extends Binder {
DeleteService getService() {
return DeleteService.this;
}
}
}
register ACTION_SCREEN_ON or ACTION_USER_PRESENT broadcast recivers for your Appliction in Service and start Service when screen is on or user is present. you can register ACTION_SCREEN_OFF broadcast reciver for stoping Service when phone screen is off to avoid battery drain by your app.as:
In manifest.xml:
<receiver android:name="com.my.AppStart">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
BroadcastReceiver :
public class AppStart extends BroadcastReceiver {
public static final String present = "android.intent.action.USER_PRESENT";
public static final String screenon = "android.intent.action.SCREEN_ON";
public static final String screenoff = "android.intent.action.SCREEN_OFF";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(present) || intent.getAction().equals(screenon) )
{
Intent i=new Intent(context,DeleteService.class);
context.startService(i);
}
if (intent.getAction().equals(screenoff))
{
//STOP YOUR SERVICE HERE
}
}
}
A service can only by started by an Activity, or a BroadCast receiver, or a service which is already started. It can't be stand-alone(It can't start by itself). So, you would need one of the two components to start it. you can make an activity which starts the service which is the preferred way. But if you don't want to provide a user interface, implement a broadcast receiver which fires up when the phone is switched on and the boot up is completed, Inside that br, start your service. This will also help you run the service as soon as a phone starts.
for example in your manifest:
<receiver android:name="com.my.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
and in the br:
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i=new Intent(context,DeleteService.class);
context.startService(i);
}
}
In your activity .. put this code in oncreate
Intent svc=new Intent(youractivity.this,DeleteService.class);
startService(svc);

BroadCastReceiver calls Service

Hi I am using this code to call a Service from BroadCastReceiver but its not working.
here is the code:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("luli");
Intent myIntent=new Intent(context,AlarmReceiver.class);
// myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(myIntent);
}
}
then on my Service I have this code:
public class AlarmService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("HEY u bastard service print at least something");
return null;
}
}
I have also declared in Manifest the service
What is wrong here that is not responding the Service??
You override onBind(). Thats only called when someone creates a persistent connection to the service via binding (Context.bindService()). You should rather override onStartCommand().

Categories

Resources