I am trying to update the UI according to change of a variable in BroadcastReceiver. Thus, I need to call a method (to get the variable I mentioned) of a class which extends BroadcastReceiver in MainActivity depending on but I cannot get the true return value in any way.
The class which extends BroadcastReceiver is this:
public class ProviderChangeReceiver extends BroadcastReceiver {
private static boolean isProviderActive;
#Override
public void onReceive(Context context, Intent intent) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER) && lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("-> ", "GPS + NETWORK");
isProviderActive = true;
}
else if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER) && !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("-> ", "GPS");
isProviderActive = true;
}
else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) && !lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v("-> ", "NETWORK");
isProviderActive = true;
}
else
{
Log.v("-> ", "DISCONNECT");
isProviderActive = false;
}
}
public static boolean isProviderActive(){
return isProviderActive;
}
}
I need to get true value of isProviderActive to use in this part of MainActivity:
...
private class ProviderChangeReceiver_updateUI extends ProviderChangeReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
MapsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("-A", ""+ isProviderActive());
if (isProviderActive())
originButton.setVisibility(View.VISIBLE);
else
originButton.setVisibility(View.INVISIBLE);
}
});
}
}
I know that indicating isProviderActive as static is not a good approach but I just want to observe its changes. As you guess, I got nonsensical return values all the time. To values of boolean isProviderActive without problem, what do you advise?
Edit: My temporary solution to update UI according to changes in BroadcastReceiver.
Forget about creating a separate class for ProviderChangeReceiver. Instead of the code segment above, following segment should be added in MainActivity. Also, it goes without saying that there is the initialization of ProviderChangeReceiver in onCreate().
...
private class ProviderChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
MapsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("COUNT: ", "" + count++);
if (isLocationProviderActive()) {
originButton.getBackground().setAlpha(220);
originButton.setEnabled(true);
//marker.setVisible(true);
}
else {
originButton.getBackground().setAlpha(77);
originButton.setEnabled(false);
marker.setVisible(false);
}
}
});
}
}
private boolean isLocationProviderActive(){
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER) && lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
return true;
return false;
}
Of course then register the receiver in onCreate() as well:
registerReceiver(pcr, new IntentFilter("android.location.PROVIDERS_CHANGED"));
The reason that every time isProvidrActive changed the whole activity got regenerated is because I sent the intent using context.startActivity(i) but rather this time we send the intent using contect.sendBroadcast(i) to the ProviderChangeReceiver_updateUI inner class which update only desired part of the UI. So below is the new code.
private static boolean isProviderActive;
#Override
public void onReceive(Context context, Intent intent) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER) && lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("-> ", "GPS + NETWORK");
isProviderActive = true;
}
else if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER) && !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("-> ", "GPS");
isProviderActive = true;
}
else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) && !lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v("-> ", "NETWORK");
isProviderActive = true;
}
else
{
Log.v("-> ", "DISCONNECT");
isProviderActive = false;
}
//Send value of isProviderActive to ProviderChangeReceiver_updateUI
Intent i = new Intent(context, ProviderChangeReceiver_updateUI.class);
i.putExtra("isProvidrActv", isProviderActive);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.sendBroadcast(i);
}
Edit your manifest file to enable the inner class ProviderChangeReceiver_updateUI to listen for broadcast sent by our broadcastReciever, add the following entry to manifest
<receiver android:name="<package-name>.MainActivity$ProviderChangeReceiver_updateUI"
android:enabled="true" >
<intent-filter>
</intent-filter>
</receiver>
the $ sign indicates inner class. No need to add intent-filters unless required.
And in your ProviderChangeReceiver_updateUI class in the onReceive() method get the value of isProviderActive
...
//changed the identifiers from private to public static and the class extends //BroadcastReceiver
public static class ProviderChangeReceiver_updateUI extends BroadcastReceiver {
//Empty constructor to prevent exception can't instantiate no empty constructor
public ProviderChangeReceiver_updateUI(){
}
//Removed the final keyword from handler
private Handler handler; // Handler used to execute code on the UI thread
public ProviderChangeReceiver_updateUI(Handler handler) {
this.handler = handler;
}
#Override
public void onReceive(final Context context, final Intent intent) {
boolean isProvidrActv = intent.getBooleanExtra("isProvidrActv", false);
//mapsActivity is a global static object of the class MapsActivity<br/>
//instantiate it the onCreate() method of mainactivity for ex:<br/>
/*public class MapsActivity extends Activity{<br/>
static MapsActivity mapsActivity;
#Override
protected void onCreate(Bundle savedInstancestate){
ma = new MapsActivity();
}*/
mapsActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (isProvidrActv)
originButton.setVisibility(View.VISIBLE);
else
originButton.setVisibility(View.INVISIBLE);
}
});
}
}
I think a nice way to handle something like this is with an eventbus.
Take a look at Squares Otto library.
In your broadcast receiver you would publish the change event and then in your activity you would subscribe to the event and update the ui.
Based on the context of your question, I think you would be able to avoid the broadcast receiver entirely, since I suspect you have something watching your provider and then broadcasting the event.
Update: (based on comments)
I think the way this would work would be something like this
In the code that detects the change in location provider:
if (bothProvidersAreStopped()) {
bus.publish(new BothProvidersStoppedEvent());
} else if (onlyNetworkProviderIsStopped() {
bus.publish(new NetworkProviderStoppedEvent());
} else if (onlyGpsProviderIsStopped() {
bus.publish(new GpsProviderStoppedEvent());
}
in your activity
#Subscribe public void onBothProvidersStopped(BothProvidersStopped event) {
// handle case were both providers just stopped
}
#Subscribe public void onNetworkProvidersStopped(BothProvidersStopped event) {
// handle case were network provider just stopped
}
#Subscribe public void onGpsProvidersStopped(BothProvidersStopped event) {
// handle case were gps provider just stopped
}
Related
I am looking for a way to check and to listen to my internet connection but since the latest Android version doesn't support registering a broadcast in Manifest, I am looking for a way to implement something that works on all the Android versions. So far I couldn't find any solutions.
I tried adding a Broadcast intent filter into my Manifest file but that's not allowed in the more recent Android versions.
<receiver
android:name="utilities.NetworkStateChangeReceiver"
android:exported="true"
android:enabled="true"
android:label="NetworkConnection" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
#Override
public void onReceive(Context context, Intent intent) {
Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
}
private boolean isConnectedToInternet(Context context) {
final ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMobile = false, isWifi = false;
NetworkInfo[] infoAvailableNetworks = cm.getAllNetworkInfo();
if (infoAvailableNetworks != null) {
for (NetworkInfo network : infoAvailableNetworks) {
if (network.getType() == ConnectivityManager.TYPE_WIFI) {
if (network.isConnected() && network.isAvailable())
isWifi = true;
}
if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
if (network.isConnected() && network.isAvailable())
isMobile = true;
}
}
}
return isMobile || isWifi;
}
}
My receiver is not able to receive a broadcast
I'm using pretty much the same logic with IntentFilter and it works for me pretty good without registering it in the Manifest file.
Interface:
public interface IReceiverStateChange {
void register(BroadcastReceiver broadcastReceiver);
void unregister(BroadcastReceiver broadcastReceiver);
}
Implementation:
public class NetworkReceiverStateChange implements IReceiverStateChange {
private Context mContext;
private Boolean mIsRegistered = false;
public NetworkReceiverStateChange(Context context) {
mContext = context;
}
#Override
public void register(BroadcastReceiver broadcastReceiver) {
if (!mIsRegistered) {
IntentFilter netWorkIntentFilter = new
IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mContext.registerReceiver(broadcastReceiver, netWorkIntentFilter);
mIsRegistered = true;
}
}
#Override
public void unregister(BroadcastReceiver broadcastReceiver) {
if (mIsRegistered) {
mContext.unregisterReceiver(broadcastReceiver);
mIsRegistered = false;
}
}
}
Register in the desired activity:
if (mNetworkStateChange == null) {
mNetworkStateChange = new NetworkReceiverStateChange(this);
}
mNetworkStateChange.register(mNetworkBroadcastReceiver);
Unregister in onDestroy:
if (mNetworkStateChange != null) {
mNetworkStateChange.unregister(mNetworkBroadcastReceiver);
}
The BroadcastReceiver Obj:
//The CONNECTIVITY_ACTION broadcast seems to be sticky on some devices (even
though the documentation implies that it is not).
// This means that when you register the receiver it will immediately call
onReceive() with the most recently sent broadcast.
private final BroadcastReceiver mNetworkBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action != null && action.matches("android.net.conn.CONNECTIVITY_CHANGE")) {
<DO SOMETHING>
}
}
};
Hope it helps :)
If you want to check your internet connection all of your activities you can follow below code :-
NetworkSchedulerService.java
public class NetworkSchedulerService extends JobService implements
ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = NetworkSchedulerService.class.getSimpleName();
private ConnectivityReceiver mConnectivityReceiver;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service created");
prefManager = PrefManager.getInstance(this);
mConnectivityReceiver = new ConnectivityReceiver(this);
}
/**
* When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
* activity and this service can communicate back and forth. See "setUiCallback()"
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return START_NOT_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartJob" + mConnectivityReceiver);
registerReceiver(mConnectivityReceiver, new IntentFilter(CONNECTIVITY_ACTION));
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob");
unregisterReceiver(mConnectivityReceiver);
return true;
}
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
Toast.makeText(this,"connected to internet",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"no internet connection",Toast.LENGTH_SHORT).show();
}
}
}
In manifest file
<service
android:name=".NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>```
create a Application class
class MyApplication extends Application {
override fun onCreate() {
super.onCreate()
scheduleJob()
}
override fun onStop() {
super.onStop()
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(Intent(this, NetworkSchedulerService::class.java))
}
override fun onStart(){
val startServiceIntent = Intent(this, NetworkSchedulerService::class.java)
startService(startServiceIntent)
}
private fun scheduleJob() {
val myJob = JobInfo.Builder(0, ComponentName(this, NetworkSchedulerService::class.java))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build()
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.schedule(myJob)
}
}
define application class in manifest file
BroadcastReceiver class ->
public class ConnectivityReceiver extends BroadcastReceiver {
private ConnectivityReceiverListener mConnectivityReceiverListener;
ConnectivityReceiver(ConnectivityReceiverListener listener) {
mConnectivityReceiverListener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
**onNetworkConnectionChanged will notify when internet is connected or not (NetworkSchedulerService.java)
Don't define BroadCastReceiver in manifest file. make sure to provide internect permission , CHANGE_NETWORK_STATE,ACCESS_NETWORK_STATE
**
I hope this will help you. Let me know if there is any problem. Happy Coding :-)
I used Toast to make notification, but it seems it will appear even its activity is not in the current screen and some other activity has been started.
I want to check this situation, when the activity is not the current one, I'd not send the Toast notification. But how to do ?
When your Activity comes to the foreground, its onResume() method will be invoked. When another Activity comes in front of your Activity, its onPause() method will be invoked. So all you need to do is implement a boolean indicating if your Activity is in the foreground:
private boolean isInFront;
#Override
public void onResume() {
super.onResume();
isInFront = true;
}
#Override
public void onPause() {
super.onPause();
isInFront = false;
}
ArrayList<String> runningactivities = new ArrayList<String>();
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i1 = 0; i1 < services.size(); i1++) {
runningactivities.add(0,services.get(i1).topActivity.toString());
}
if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show();
}
This way you will know if the pointed activity is the current visible activity.
I prefer not to handle the state by myself, so I have implemented a class that does this for me.
package mypackage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
// Mine extends AppCompatActivity - your's might need to extend Activity, depending on whether
// you use the support library or not.
public class StateTrackingActivity extends AppCompatActivity {
public enum ActivityState {
CREATED, RESUMED, STARTED, PAUSED, STOPPED, DESTROYED
}
private ActivityState _activityState;
protected ActivityState getActivityState() { return _activityState; }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activityState = ActivityState.CREATED;
}
#Override
protected void onResume() {
super.onResume();
_activityState = ActivityState.RESUMED;
}
#Override
protected void onStart() {
super.onStart();
_activityState = ActivityState.STARTED;
}
#Override
protected void onPause() {
super.onPause();
_activityState = ActivityState.PAUSED;
}
#Override
protected void onStop() {
super.onStop();
_activityState = ActivityState.STOPPED;
}
#Override
protected void onDestroy() {
super.onDestroy();
_activityState = ActivityState.DESTROYED;
}
}
Then your activity can extend this one and you can get the state by calling getActivityState().
This is my ultimate isActivityVisible function.
protected boolean isActivityVisible() {
if (this.mActivity != null) {
Class klass = this.mActivity.getClass();
while (klass != null) {
try {
Field field = klass.getDeclaredField("mResumed");
field.setAccessible(true);
Object obj = field.get(this.mActivity);
return (Boolean)obj;
} catch (NoSuchFieldException exception1) {
// Log.e(TAG, exception1.toString());
} catch (IllegalAccessException exception2) {
// Log.e(TAG, exception2.toString());
}
klass = klass.getSuperclass();
}
}
return false;
}
if (BaseActivity.this instanceof Faq)
{
Toast.makeText(BaseActivity.this, "You are in the Same Page", Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(BaseActivity.this, Faq.class);
startActivity(intent);
drawer.closeDrawer(GravityCompat.START);
}
//// here am All my activities are extending on Activity called BaseActivity
There is Activity#isTaskRoot() method
if ( getActivity() instanceof ManageCardActivity){
// your code
}
I'm trying to implement service in android to make an app locker.
I'm trying to check the which activity is running on the foreground and if it's locked, forwarding it to my Locker activity.
I've added the service in manifest too, but it isn't working at all.
Here's the code `
private static Timer timer = new Timer();
public Boolean userAuth = false;
private Context mContext;
public String pActivity = "";
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate() {
super.onCreate();
mContext = this;
startService();
}
private void startService() {
timer.scheduleAtFixedRate(new mainTask(), 0, 500);
}
private class mainTask extends TimerTask {
public void run() {
toastHandler.sendEmptyMessage(0);
}
}
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler toastHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String activityOnTop;
ActivityManager manager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = manager.getRunningAppProcesses();
//Getting the foreground activity name
activityOnTop=tasks.get(0).processName;
//Checking it against the app I need to lock
if (activityOnTop.equalsIgnoreCase("com.droiddigger.techmanik")) {
Intent lockIntent = new Intent(mContext, Lockscreen.class);
lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(lockIntent);
} else if(activityOnTop.equalsIgnoreCase("com.droiddigger.applocker")){
}else{
}
}
};
You must start that service. It can be done in an Activity or a BroadcastReceiver.
startService(new Intent(this, UpdaterServiceManager.class));
For example:
public class MyActivity extends Activity {
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, YourService.class));
finish();
}
}
EDIT:
You are always retrieving the item 0 of the list called tasks. Looking at the SDK documentation, it is said that list order is not especified: https://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses()
Returns a list of RunningAppProcessInfo records, or null if there are
no running processes (it will not return an empty list). This list
ordering is not specified.
You must get the current visible activity other way. I suggest an AccessibilityService
I am working on a prototype Android app that sends gps data to a server. I had something working when I called my class GetLocation directly from my MainActivity class. However, I would want this to really work as a background service. I tried using similar code, but for some reason the LocationListener's functions never get called (the only one I'm looking at is the onLocationChanged). Am I misunderstanding how this works? Thanks. Here's my code.
public class GetLocation {
...
public GetLocation(Context myContext, String hostParam)
{
this.context = myContext;
sendMessage = false;
sendData = new SendData(Constants.HOST_NAME);
locationManager = (LocationManager) context.getSystemService((Context.LOCATION_SERVICE));
this.host = hostParam;
locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
String sentence = AssembleSentence.assembleNMEAURL(location);
//sendData.sendMessage(sentence);
int geozoneLocation = GeoZone.getGeozoneLocation(location);
switch(geozoneLocation)
{
case GeoZone.LEVEL_ONE:
sendMessage = false;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_ONE_INTERVAL, LocationManager.NETWORK_PROVIDER);
}
break;
case GeoZone.LEVEL_TWO:
sendMessage = false;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_TWO_INTERVAL, LocationManager.NETWORK_PROVIDER);
}
break;
case GeoZone.LEVEL_THREE:
sendMessage = false;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_THREE_INTERVAL, LocationManager.NETWORK_PROVIDER);
}
break;
case GeoZone.LEVEL_FOUR:
sendMessage = true;
if(Constants.LEVEL_ONE_INTERVAL != currentInterval)
{
startLocationUpdates(Constants.LEVEL_FOUR_INTERVAL, LocationManager.GPS_PROVIDER);
}
break;
}
if(sendMessage)
{
sendData.sendMessage(sentence);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
};
}
....
}
Which is called by my Service class below.
public class TelematicsIntent extends Service
{
public TelematicsIntent()
{
}
#Override
public IBinder onBind(Intent intent)
{
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate()
{
GetLocation location = new GetLocation(this, Constants.HOST_NAME);
}
#Override
public void onDestroy()
{
}
}
And this Service class is called by the MainActivity class. I know that the GetLocation class is being called correctly, as I set up a break point in the
this.host = hostParam and the code stopped there, but I put another break point in the statement int geozoneLocation = GeoZone.getGeozoneLocation(location); where GeoZone class is another class that just goes through the location data and returns whether the location is inside a particular area. Any ideas?
I figured out why it wasn't being called. I forgot to actually start the location services, as I had no way in the code for them to actually start. I should have seen this earlier, but I guess I didn't.
i am developing an android app, where i am registering my ContentObserver class to detect
the changes in VOLUME_RING.
My problem is, i am calling the ContentObserver class upon bootup of the phone, and i am able to get inside the Contentobserver class, but the onchange method is not getting called(i.e, the changes in volume is not getting detected).
Please check out the code below,
//BootupReceiver code.
public class Bootupreceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent startServiceIntent = new Intent(context,ServiceforVolumeChecker.class);
startServiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(startServiceIntent);
}
}
//code to register the Content observer class.
public class ServiceforVolumeChecker extends Service
{
private VolumeChecker Volume;
#Override
public void onCreate()
{
super.onCreate();
Log.e("Service","Service");
Volume = new VolumeChecker(this,new Handler());
String vol_ring = android.provider.Settings.System.VOLUME_RING;
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= 17)
{
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, Volume );
}
else
{
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.getUriFor(vol_ring), true, Volume);
}
stopService(new Intent(this, ServiceforVolumeChecker.class));
}
#Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
//code of ContentObserver class.
public class VolumeChecker extends ContentObserver
{
public VolumeChecker(Context c, Handler handler)
{
super(handler);
context=c;
this.handler = handler;
}
#Override
public boolean deliverSelfNotifications()
{
return super.deliverSelfNotifications();
}
#Override
public void onChange(boolean selfChange)
{
super.onChange(selfChange);
}
Please help! Thanks!
Put the service task in onStartCommand instead of using onCreate