I want that the service is running even if the application is closed ( killed ) or even if the user does not start the application . I want to start the service after the application is installed and from this point , the service requires to run constantly every ten minutes.
Although I found some solutions such as
- Android Service needs to run always (Never pause or stop)
- Android - Run a service in background even when app is killed or device rebooted
- How to run android service permanently like system service?
those are not working to me as I am new in Android programming. If there is any sample working source code, please provide me the information how to develop it.
Here is my Service Class..
public class MyService extends Service {
MyReceiver receiver = new MyReceiver();
public void onCreate()
{
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
receiver.SetAlarm(this);
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startId)
{
receiver.SetAlarm(this);
}
}
Here is my Receiver Class..
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}catch (Exception e) {
e.printStackTrace();
}
}
public void SetAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, UploadLocReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
}
I added service and receiver in AndroidManifest.xml file.
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service android:name=".MyService"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
I've added below codes in my Main Activity.
Intent service = new Intent(getApplicationContext(), MyService.class);
this.startService(service);