I use activity recognition api and activity transitions. When I first run the app, the first transition is always the. In this app it's WALKING-ENTER. When I tried with only IN_VEHICLE-ENTER and IN_VEHICLE-EXIT in transitions, it was IN_VEHICLE-ENTER. I thought about ignoring the first transition but a device I've tested on didn't have such a problem. The devices that had these problem were Android 8.1, and the device didn't have the problem was 6.0.
MainActivity extends AppCompatActivity
private static Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
if(!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
Button button = findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
serviceIntent = new Intent(MainActivity.this, ServiceS.class);
MainActivity.this.startService(serviceIntent);
}
});
}
public static boolean hasPermissions(Context context, String... permissions) {
if (permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
ServiceS extends Service
public ServiceS() {
super();
}
public static void locationArrived(Context context, Location location) {
Log.d("hmm: ", location.toString());
}
#SuppressLint("MissingPermission")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
initActivityTransition();
super.onCreate();
}
#Override
public void onDestroy() {
Log.d("hmm: ", "Updates stopped!");
Task task = ActivityRecognition.getClient(this)
.removeActivityTransitionUpdates(activityPendingIntent);
super.onDestroy();
}
// ACTIVITY TRANSITION BLOCK START
private static List<ActivityTransition> transitions = new ArrayList<>();
private static PendingIntent activityPendingIntent;
private static ActivityTransitionRequest transitionRequest;
void initActivityTransition(){
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.WALKING)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.WALKING)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.STILL)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build());
transitions.add(
new ActivityTransition.Builder()
.setActivityType(DetectedActivity.STILL)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build());
Intent activityIntentService = new Intent(this, TransitionReceiver.class);
activityPendingIntent = PendingIntent.getBroadcast(this, 1, activityIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d("hmm: ","DriveBuddyService - initActivityTransition");
}
static void transitionArrived(final ActivityTransitionEvent event, final Context context){
Log.d("hmm: ", event.toString());
Toast.makeText(context, event.getActivityType() + "-" + event.getTransitionType(), Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
if(transitionRequest==null) {
transitionRequest = new ActivityTransitionRequest(transitions);
}
Task task = ActivityRecognition.getClient(this)
.requestActivityTransitionUpdates(transitionRequest, activityPendingIntent);
super.onStart(intent, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
TransitionReceiver extends BroadcastReceiver.
public void onReceive(final Context context, Intent intent) {
Log.d("hmm: ","DriveBuddyTransitionReceiver - Enter");
if (ActivityTransitionResult.hasResult(intent)) {
ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
for (ActivityTransitionEvent event : result.getTransitionEvents()) {
ServiceS.transitionArrived(event, context);
}
}
}
I observed the same thing too. It seems that the last activity is kept in cache or something like that. I saw this happening on Android 7.1 and Android 8.1.
To counter this I check the elapsed time of when the transition happened. I ignore the callback if the transition happened over 30 seconds ago.
This is what my code looks like:
#Override
public void onReceive(Context context, Intent i) {
if (ActivityTransitionResult.hasResult(i)) {
ActivityTransitionResult result = ActivityTransitionResult.extractResult(i);
for (ActivityTransitionEvent event : result.getTransitionEvents()) {
//continue only if the activity happened in the last 30 seconds
//for some reason callbacks are received for old activities when the receiver is registered
if(((SystemClock.elapsedRealtime()-(event.getElapsedRealTimeNanos()/1000000))/1000) <= 30) {
//activity transition is legit. Do stuff here..
}
}
}
}
I've typically seen callbacks arrive 0-10 seconds of them occurring.
Related
Let's pretend that I have a flutter application and I have a Foreground Service that has a worker thread and keeps sending me updates about user's location, this is the service's code which returns a random integer numbers for now :
Android Service code
public class LocationUpdatesService extends Service {
static final int NOTIFICATION_ID = 100;
static final String NOTIFICATION = "com.example.fitness_app";
NotificationManagerCompat m_notificationManager;
private Intent m_broadcastInent;
private final String TAG = this.getClass().getSimpleName();
private AtomicBoolean working = new AtomicBoolean(true);
private int steps = 0;
private Runnable runnable = new Runnable() {
#Override
public void run() {
while(working.get()) {
steps++;
m_notificationManager.notify(NOTIFICATION_ID,
createNotification("Steps Counter" + steps ,
R.drawable.common_full_open_on_phone, 1));
m_broadcastInent.putExtra("steps", steps);
sendBroadcast(m_broadcastInent);
}
}
};
#Override
public void onCreate() {
m_broadcastInent = new Intent(NOTIFICATION);
m_notificationManager = NotificationManagerCompat.from(this);
createNotificationChannel();
startForeground(NOTIFICATION_ID, createNotification("Steps Counter" ,
R.drawable.common_full_open_on_phone, 0));
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(runnable).start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
working.set(false);
m_notificationManager.cancel(NOTIFICATION_ID);
super.onDestroy();
}
private Notification createNotification(String title, int icon, int steps) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID));
builder.setNumber(steps);
builder.setSmallIcon(icon);
builder.setContentTitle(title);
builder.setOnlyAlertOnce(true);
return builder.build();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID);
String description =
getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_DESCRIPTION);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel =
new NotificationChannel(getString(
R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID), name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
In MainActivity.java I am recieving broadcasts from the service and I should send them to the flutter side:
MainActivity
public class MainActivity extends FlutterActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String ONE_TIME_BACKGROUND_METHOD_CHANNEL = "fitness_app/method_one_time_service";
private static final String EVENTS_STREAM_CHANNEL = "fitness_app/event_one_time_service";
private Intent m_serviceIntent;
private MethodChannel m_methodChannel;
private EventChannel m_eventchannel;
private EventChannel.EventSink m_stepsStreamSink;
private EventChannel.StreamHandler m_eventCallHandler;
private MethodChannel.Result m_result;
private EventChannel.EventSink m_eventSink;
private BroadcastReceiver m_serviceBroadcastReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "milliseconds " + intent.getIntExtra("steps", 0));
Bundle bundle = intent.getExtras();
if (bundle != null) {
int steps = bundle.getInt("steps");
/////////////////////////////////////////
/////////////////////////////////////////
// I need Here To add Data To the stream
/////////////////////////////////////////
/////////////////////////////////////////
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
m_serviceIntent = new Intent(this, LocationUpdatesService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, m_serviceIntent, 0);
m_methodChannel = new MethodChannel(getFlutterView(), ONE_TIME_BACKGROUND_METHOD_CHANNEL);
m_methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("START_STEPS_COUNTER")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(m_serviceIntent);
} else {
startService(m_serviceIntent);
}
} else {
stopService(m_serviceIntent);
}
}
});
m_eventchannel = new EventChannel(getFlutterView(), EVENTS_STREAM_CHANNEL);
m_eventCallHandler = new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
m_eventSink = eventSink;
}
#Override
public void onCancel(Object o) {
}
};
m_eventchannel.setStreamHandler(m_eventCallHandler);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(m_serviceBroadcastReciever, new IntentFilter(LocationUpdatesService.NOTIFICATION));
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Flutter dart code
void start() async {
try {
await _methodChannel.invokeMethod(PlatformMethods.STEPS_COUNTER_START);
Stream<int> stream = _eventChannel.receiveBroadcastStream();
} on PlatformException catch (e) {
print(
" Faild to run native service with thrown exception : ${e.toString()}");
}
Everything here works fine. I can Trigger the service using the Methodchannel, I receive the data from the service using the BroadCastREciever.
All I need to do is to return a stream from the native code using EventChannel.
Create a class that extends BroadcastReceiver and pass a EventChannel.EventSink.
class SinkBroadcastReceiver(private val sink: EventChannel.EventSink) {
override fun onReceive(context: Context, intent: Intent) {
val bundle = intent.getExtras()
if (bundle != null) {
val steps = bundle.getInt("steps")
sink.success(steps)
}
}
}
Then, instead od create the BroadcastReceiver in the declaration you can create it in the onListen and call registerReceiver there:
m_eventCallHandler = new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
SinkBroadcastReceiver receiver = new SinkBroadcastReceiver(eventSink);
registerReceiver(receiver, new IntentFilter(LocationUpdatesService.NOTIFICATION));
// TODO : Save receiver in a list to call unregisterReceiver later
}
#Override
public void onCancel(Object o) {
}
};
You may need to track all the receivers in a list because you may need to unregister when the activity stops. Also when you stop the service you may need to traverse the list of registered BroadcastReceiver to unregister all the instances.
This way you may also have more than one listener on the dart code for the same event.
I am using a Service for performing some task, which should run only if the app is in background, moreover the service runs for sometime and after sometime, it gets destroyed. Earlier this was working completely fine, but don't know where i am doing wrong.
Here is the code of my Service:
public class MyService extends Service {
Context context;
public static final String TAG = MyService.class.getSimpleName();
public MyService(Context applicationContext) {
super();
context = applicationContext;
Log.i("myservice", "here service created!");
}
public MyService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "[onCreateService]");
super.onStartCommand(intent, flags, startId);
// Code
registerOverlayReceiver();
context = this;
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterOverlayReceiver();
Log.i("EXIT", "ondestroy!");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void unregisterOverlayReceiver() {
if (myReceiver != null) {
unregisterReceiver(myReceiver);
}
}
private static final String ACTION_DEBUG = "abc.action.DEBUG";
private void registerOverlayReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(ACTION_DEBUG);
registerReceiver(myReceiver, filter);
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "[onReceive]" + action);
if (action.equals(Intent.ACTION_SCREEN_ON)) {
showMyActivity();
} else if (action.equals(ACTION_DEBUG)) {
showMyActivity();
}
}
};
private void showMyActivity() {
Intent intent = new Intent();
intent.setClass(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
I have debugged but couldn't find out the problem for the same.
Anybody who came across anything like this can help me out.
I am having an activity and on Launching the activity through Intent from one of my service, onCreate(), onPause() and onResume() is called.
I am not very sure where i am doing wrong, i have removed all the code, just the basic function codes are available, and also i have removed all the codes which were opening that particular activity, still the behaviour is same.
I am including the simplest code i am using
ActivityClass.java
public class ActivityClass extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("TEST : onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lockscreen);
ButterKnife.bind(this);
}
#Override
protected void onPause() {
System.out.println("TEST : onPause");
super.onPause();
}
#Override
protected void onDestroy() {
System.out.println("TEST : onDestroy");
super.onDestroy();
}
}
Service class
public class OverlayService extends Service {
Context context;
public static final String TAG = OverlayService.class.getSimpleName();
public OverlayService(Context applicationContext) {
super();
context = applicationContext;
}
public OverlayService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "[onCreateService]");
super.onStartCommand(intent, flags, startId);
KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
if(myKM.inKeyguardRestrictedInputMode()) {
//it is locked
showOverlayActivity();
} else {
//it is not locked
}
registerOverlayReceiver();
context = this;
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterOverlayReceiver();
Log.i("EXIT", "ondestroy!");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void unregisterOverlayReceiver() {
if (overlayReceiver != null) {
unregisterReceiver(overlayReceiver);
}
}
private static final String ACTION_DEBUG = "kunal.lockoverlay.action.DEBUG";
private void registerOverlayReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(ACTION_DEBUG);
registerReceiver(overlayReceiver, filter);
}
private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "[onReceive]" + action);
if (action.equals(Intent.ACTION_SCREEN_ON)) {
// ACTON_SCREEN_ON
showOverlayActivity();
} else if (action.equals(ACTION_DEBUG)) {
showOverlayActivity();
}
}
};
private void showOverlayActivity() {
Intent intent = new Intent();
intent.setClass(this, ActivityClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Can someone point some of the possible reasons for this behaviour or could identify where i am doing wrong?
Well everything will be called regardless, you have defined it in your ClassName.java file.
You override the method and define it in your class to perform certain action/function when that is called.
For eg.,
You could use onResume to clear an arraylist and add updated elements to arraylist (OR) dismiss all notifications from your app on moving to that activity, say
#Override
public void onResume() {
super.onResume();
calendarList.clear();
//dismiss all notifications here
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager!=null)
notificationManager.cancelAll();
}
OR eg., onDestroy to destroy the bluetooth service,
#Override
public void onDestroy() {
super.onDestroy();
if (mBluetoothService != null) {
mBluetoothService.stop();
}
}
Hope that clarifies. Happy coding!
About service class, you should call registerReceiver() or initialize variables in onCreate instead of onStartCommand because onCreate is only called once at the first time of starting service and onStartCommand will be called every time you want to trigger an action to the service by calling startService(Intent).
I have created a service that has a LocationListener.
In the Fragment i have a BroadcastReceiver that successfully receives location from the Service. Everything works fine when the phone is connected to my computer and I have pressed "run" (not debug mode). I receive location continuously when the screen on my phone is turned off as I can see in the "Run" console in Android Studio.
However when i disconnect my phone from the computer and turn the screen off, I stoped receiving location updates. Or I got only one or two location updates before it stoped. Then when turning the screen on again the Service starts sending location updates.
I have tried using a WakeLock on the Fragment and the Service, but it dosent seem to have any effect.
Can someone help me please!?... :,(
In my Service I set a ArrayList->String in putExtra() that contains a Latitude and a TimeStamp so that I can see if the locationlistener did update location when screen is locked. And in the Fragment I display the results in the view so that I can manually debug.
Here is my Service code:
public class GpsService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private Intent mIntent;
private ArrayList<String> latTimeArrayList = new ArrayList<>();
private PowerManager.WakeLock wakeLock;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
mIntent = new Intent("location_update");
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
return START_NOT_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mIntent.putExtra("Latitude", location.getLatitude());
mIntent.putExtra("Longitude", location.getLongitude());
if(latTimeArrayList.size() < 10){
latTimeArrayList.add(location.getLatitude() + " -> " + new Date());
}else if(latTimeArrayList.size() == 10){
mIntent.putExtra("latTimeArray", latTimeArrayList);
}
sendBroadcast(mIntent);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
wakeLock.release();
}
}
}
private BroadcastReceiver broadcastReceiver;
ArrayList<String> aString = new ArrayList<>();
private String mmtext = "";
TextView debugtext = (TextView) mView.findViewById(R.id.hasCompletedTrack);
int doagain = 0;
#Override
public void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try{
if (doagain == 0){
aString = (ArrayList<String>)intent.getExtras().get("latTimeArray");
if(aString != null || aString.size() != 0){
for (int i =0; i< aString.size(); i++){
mmtext += aString.get(i) + "\n";
}
doagain = 1;
debugtext.setText(mmtext);
}
}
}catch(NullPointerException e){}
I found the answer...
I had to turn off PoweSaving mode on my Samsung Galaxy S6 edge.
Also, in my broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
that's in my Fragment, I did some position calculations for every location update that I got from my Service with a Intent getExtra() (this is not in the code I posted). However onReceive() only gets triggered when the screen is on(not locked). Therefore my calculations in the fragment were never triggered, only when the screen was on it triggered the calculation methods.
My solution to this was to handle all the calculations directly in my service.
I try to send data to server every 15 seconds so i used broadcast receiver and Android service but it did not work any more.I check Internet Connection Every 15 second and when connection is available it send data to server.
Test.java
public class Test extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
this.context = this;
Intent alarm = new Intent(this.context, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(alarmRunning == false) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 15000, pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, BackgroundService.class);
context.startService(background);
}
}
BackgroundService.java
public class BackgroundService extends Service {
private boolean isRunning;
private Context context;
private Thread backgroundThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
public void run() {
// Do something here
internet();
System.out.println("call every 15 seconds");
Log.d("Background","Services run every 15 second");
stopSelf();
}
};
#Override
public void onDestroy() {
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
private void internet() {
Helper hp = new Helper(context);
if (hp.isonline() == true) {
System.out.println("net connect");
} else {
System.out.println("net not available");
}
}
}
}
Manifest.xml
<service android:name=".service.BackgroundService" />
<receiver android:name=".service.AlarmReceiver"></receiver>
hole code return in logcat print message only one time, not every 15 seconds.