Search code examples
androidservicealarmmanagersmsmanager

android: how to start a service


I have an app which sends auto sms after a specific time.I want it to always run in the background and when I restart the phone it should start the process automatically. It worked fine when I extend it with Activity. Kindly tell me how should I start it with Service.

the code of service class

public class MainActivity extends Service {

@Override
public void onCreate() {
    //super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    startLocationTracking();
}

private void startLocationTracking()
{
    AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);

    Intent alarmintent1=new Intent(MainActivity.this, AlarmReceiver.class);

    PendingIntent sender1=PendingIntent.getBroadcast(MainActivity.this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

    try {
        am.cancel(sender1);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("exjfkd"+e);
    }

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND,5);


    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*180, sender1);
    System.out.println("set timer");
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

}

code of second class

public class AlarmReceiver extends BroadcastReceiver{

long time = 180 * 1000; 
long distance = 10; 

@SuppressLint("NewApi") 

@Override
public void onReceive(final Context context, Intent intent) {

    System.out.println("alarm receiver....");

    LocationManager locationManager = (LocationManager)context
            .getSystemService(Context.LOCATION_SERVICE);


    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    locationManager.requestLocationUpdates(provider, time,
            distance, locationListener);

   Location location = locationManager.getLastKnownLocation(provider);

    String phoneNo = "+96987978";
    String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude();

    try {
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(phoneNo, null, Text, null, null);
    Log.i("Send SMS", "");

    Toast.makeText(context, "message sent", Toast.LENGTH_SHORT).show();

 } catch (Exception e) {
    Toast.makeText(context, "SMS faild, please try again.",
    Toast.LENGTH_LONG).show();
    e.printStackTrace();
 } 

}

LocationListener locationListener = new LocationListener() {

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }
};



 }

AndroidManifest file

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >



    <service android:enabled="true" 
        android:name="com.example.locationupdates.services.MainActivity" >
    <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
       </service>

    <receiver android:name="com.example.locationupdates.AlarmReceiver" >
    <intent-filter android:priority="100">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
    </receiver>
</application>


Solution

  • Try something like this,

    public class HandlerService extends Service
    {
        private final IBinder mBinder = new MyBinder();
        @Override
        public IBinder onBind( Intent arg0 )
        {
            return mBinder;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
    
            //your stuff
    
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public void onCreate() {
           Log.d( "oncreated", "oncreated" );
        }
    
        @Override
        public void onDestroy() {
    
        }
    
        public class MyBinder extends Binder {
            HandlerService getService() {
            return HandlerService.this;
          }
        }
    
    }
    

    This is the broadcast receiver

    public class BootCompleteReceiver extends BroadcastReceiver {
    
          @Override
          public void onReceive(Context context, Intent intent) {
    
              Log.d("BootCompleteReceiver", "BootCompleteReceiver");
    
              Intent service = new Intent(context, HandlerService.class);
              context.startService(service);
    
          }
    }
    

    where HandlerService is the service class. Create new class for the service and register it in the manifest file. Add those lines inside the application node.

    <receiver android:name="come.code.BootCompleteReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    

    where come.code is the package of BootCompleteReceiver class