I used a Service class in my application. It works fine at other versions, but when I tested it in 5.0.2, it works fine when the application is in running state. But when I closed my Application, the service is stopped. I need the service to run continuously in background.
Here is my Service class:
public class ServiceClass extends Service{
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
UpdateLocation();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void UpdateLocation() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Thread thread = new Thread() {
#Override
public void run() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
if (mLastLocation != null) {
Log.e("lat", String.valueOf(latitude));
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
}
GetLocationUpdate();
}
};
thread.start();
}
}, 0, UPDATE_TASK);
}
}
This is my WakefulBroadcastReceiver
public class BootCompleteReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, ServiceClass.class);
context.startService(service);
}
}
My Manifest File
<service android:name=".service.ServiceClass" />
<receiver android:name=".service.BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
Thanks in advance and please help me.
Related
I'm having a really strange issue, the broadcast receiver is not working on my own device but is on the android emulator.
What does my application is restarting the service by calling the broadcast receiver everytime onDestroy method is called.
I even tried to look at developer option on my device to see if the was some restriction activated like "not keep activities", but it was unchecked.
Xml file
<service
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorService"
android:enabled="true">
</service>
<receiver
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="SensorRestarterBroadcastReceiver" />
</intent-filter>
</receiver>
Service
public class SensorService extends Service {
private Timer timer;
MyThread myThread;
private TimerTask timerTask;
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myThread = new MyThread();
myThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent restartService = new Intent("SensorRestarterBroadcastReceiver");
sendBroadcast(restartService);
timer.cancel();
myThread.interrupt();
}
public class MyThread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
int delay = 10000; // delay for 10 sec.
int period = 10000; // repeat every 10 sec.
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ "+ (counter++));
}
}, delay, period);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Brodcast Receiver
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(),
"Restarting Service");
context.startService(new Intent(context, SensorService.class));;
}
}
i want when boot run app server allow for receive message any time
without showing application
this code problem when boot show Notification twice only
but i want receive message any time
Is this "android:exported" important, What used
code AndroidManifest
<service
android:name=".appService"
android:exported="true"
android:enabled="true">
</service>
<receiver
android:name=".ServiceStarterBoot"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
code BroadcastReceiver
public class ServiceStarterBoot extends BroadcastReceiver {
private Context context ;
#Override
public void onReceive(Context context1, Intent intent) {
this.context = context1;
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceLauncher = new Intent(context, appService.class);
context.startService(serviceLauncher);
}}
code Service
public class appService extends Service {
#Override
public void onCreate() {
super.onCreate();
lood();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
//return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
private void lood(){
SystemClock.sleep(3000);
Runnable runnable = new Runnable() {
public void run() {
boolean p= true ;
while(p) {
SystemClock.sleep(5000);
showNotification();
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
please help
thanks
you have to make your service sticky:
Service.START_STICKY
then it is infinite and restarts itself when killed by OS for any reason.
It even starts itself when booting OS and app is NOT opened by user.
Best regards.
pseudo code:
onStartCommand(..){
...
//e.g. wifilisterner
Wifilistener WF = new Wifilistener(Interface yourInterfaceCallBackMethod);
}
something like this.
I'm new on android developing. I need to make a service to start when gps activated.
That's what I've done so far:
service:
public class MainService extends Service implements LocationListener {
private LocationManager locationManager;
Intent i;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 1, this);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLocationChanged(Location location) {
String msg = "New Latitude: " + location.getLatitude()
+ "New Longitude: " + location.getLongitude();
Log.d("",msg);
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Log.i("", "------------------->GPS is off");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("", "------------------->Gps is turned on!! ");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Broadcast Receiver:
public class GPSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("", "Receiver is on");
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// react on GPS provider change action
Intent serviceIntent = new Intent(context, MainService.class);
context.startService(serviceIntent);
}
}
}
Manifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver
android:name="gr.dit.hua.it21370.gpsreciever.GPSReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name="gr.dit.hua.it21370.gpsreciever.MainService"
android:process=":gps_service">
</service>
</application>
I've tried and I've searched a lot but I didn't manage to fix it.
Please help me.
Thanks in advance :)
I am trying to create a service that will run on bootup, however when trying it in my emulator the log is not showing my message through log tag, so clearly something is wrong.
Here is my code.
service.java
public class service extends Service {
private static final String TAG = "myapp.mycomp";
public service() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service started");
Runnable r = new Runnable() {
#Override
public void run() {
/** something to do **/
}
};
Thread service = new Thread(r);
service.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
Log.i(TAG, "Service stopped");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, service.class);
context.startService(myIntent);
}
}
XML manifest intent
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
XML manifest permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
I have this Service class:
public class BluetoothService extends Service {
private static Activity mActivity;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(bluetoothReceiver, intentFilter);
}
#Override
public void onDestroy() {
if (bluetoothReceiver != null) {
this.unregisterReceiver(bluetoothReceiver);
}
}
#Override
public void onStart(Intent intent, int startid) {
//
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public static BroadcastReceiver bluetoothReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
TextView tvStatus = (TextView) mActivity.findViewById(R.id.tvtatus);
Messaging.appendMessage(tvStatus, Bluetooth.getDeviceState(state));
if (Bluetooth.isBluetoothEnabled()) {
Messaging.appendMessage(tvStatus, Bluetooth.showMessage());
}
}
}
};
}
And in my Activity class, I have this:
public class MainActivity extends Activity {
private TextView tvStatus;
private Intent intentBluetooth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = (TextView)findViewById(R.id.tvtatus);
intentBluetooth = new Intent(this, BluetoothService.class);
startService(intentBluetooth);
}
}
The BroadcastReceiver method (bluetoothReceiver) in the Service class is never called. I don't know why. If I have the IntentFilter and the BroadcastReceiver codes above all in an Activity, then it works - but not in a [separate] Service. I'm stumped.
My AndroidManifest.xml is:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.onegoal.androidexample"
android:versionCode="1"
android:versionName="1.0.0"
android:installLocation="auto"
android:hardwareAccelerated="true">
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:debuggable="true" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BluetoothService">
</service>
</application>
</manifest>
I'm new to Android so what I'm doing may not be the best. Hope someone can help me.
maybe the fact that your receiver is static causing the problem.
BroadcastReceiver should never be static. it can cause lots of problems.
other really bad design problem with your code - holding reference to activity inside service, and using it to modify views is really wrong thing to do. it can cause easily to memory leek.
the right why to communicate between Service and Activity is by implement android's Messanger, or sending broadcasts between them via BroadcastReceiver.
if you'll listen to my advice - you won't be have to make your receiver static (I guess you've made it static only because you are using the mActivity static instance inside)
and I'm pretty sure it will solve your problem
you can read about Messanger here: http://developer.android.com/reference/android/os/Messenger.html
sure you'll find lots of usage examples in the net.
example of broadcasting updates to the activity from service:
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(bluetoothReceiver, intentFilter);
}
#Override
public void onDestroy() {
if (bluetoothReceiver != null) {
this.unregisterReceiver(bluetoothReceiver);
}
super.onDestroy();
}
public BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
updateUIWithNewState(state);
}
}
};
protected void updateUIWithNewState(int state) {
Intent intent = new Intent("serviceUpdateReceivedAction");
intent.putExtra("state", state);
sendBroadcast(intent);
}
}
and that's the activity:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mServiceUpdatesReceiver, new IntentFilter("serviceUpdateReceivedAction"));
}
#Override
protected void onPause() {
unregisterReceiver(mServiceUpdatesReceiver);
super.onPause();
}
private BroadcastReceiver mServiceUpdatesReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra("state", -1);
// do what ever you want in the UI according to the state
}
};
}