0

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>

Himanshu Agarwal
  • 4,623
  • 5
  • 35
  • 49
Andrain
  • 872
  • 1
  • 16
  • 43
  • Already asked go through this link 'http://stackoverflow.com/questions/5290141/android-broadcastreceiver-on-startup' – Utpal Sharma Oct 14 '14 at 07:27
  • see the following link may it will help you, http://stackoverflow.com/questions/18299700/start-my-service-on-phone-restart-in-android – MFP Oct 14 '14 at 07:28

3 Answers3

1

You need to create Boot Receiver like this:

public class MyReceiver extends BroadcastReceiver {   

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

     Intent myIntent = new Intent(context, YourService.class);
     context.startService(myIntent);
    }
}

And add this in your AndroidManifest.xml

<!-- Declaring broadcast receiver for BOOT_COMPLETED event -->
    <receiver android:name=".MyReceiver " android:enabled="true" android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>

</application>

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Himanshu Agarwal
  • 4,623
  • 5
  • 35
  • 49
0

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

0

You may want to use a ServiceConnection to check when your service is really starting and bind it if you want to keep interacting with it

    private Service mService;

    private ServiceConnection mServiceConnexion = new ServiceConnection() {

       @Override
       public void onServiceDisconnected(ComponentName name) {
         mService = null;
       }

       @Override
       public void onServiceConnected(ComponentName name, IBinder binder) {
          if (mService == null) {
             mService = (Service) ((Service.Binder) binder).getServiceInstance();
          }
          Intent intent = new Intent(ActivityPlayer.this, ServiceStreaming.class);
          startService(intent);
        }
    };


    private void bindService() {
      if (mServiceConnexion != null) {
        bindService(new Intent(Activity.this, Service.class), mServiceConnexion, Context.BIND_AUTO_CREATE);
      }
    }

Just call bindServices() in onCreate or onResume(), in this case you would want to unbind it in onPause()

Note that you can call StartService() as many times as you want it does't matter, it will just call onStartCommand() each time

An-droid
  • 6,433
  • 9
  • 48
  • 93