How to stop service in background with toggle button in Android? - java

I'm implementing running the service in background and service will be stop and start click on toggle button.Service is start in 1st activity and stop the service in another activity when click on toggle button.When i run the application service is automatically start in 1st activity which i start in onCreate() method in 1st activity and another activity toggle button status is already on status but when i toggle button is going to off service stop but when i back to 1st activity service is again start.Please can any one help me.Here is my code
public class MyService extends Service
{
private static final String TAG = "MyService";
MediaPlayer player;
private final String StrMyService="myservice";
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
public class Service_Demo extends Activity implements OnClickListener
{
private static final String TAG = "ServicesDemo";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("In OnCreate(");
startService(new Intent(this, MyService.class));
}
}
public class Toggle_Activity extends Activity
{
ToggleButton tgButton;
private boolean isService=false;
private String strService;
public final String service_Prefs="servicePrefs";
private static final String StrMyService = "zdf";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.toggle);
final SharedPreferences servicePrefs=this.getSharedPreferences("Service_Prefs",MODE_WORLD_READABLE);
strService=servicePrefs.getString(StrMyService , "myservice");
Log.e("",""+strService);
final boolean mBool = servicePrefs.getBoolean("myservice", true);
Log.e("Boolean Value mBool","="+mBool);
Boolean b = mBool;
Log.e("Update pref", b.toString());
tgButton = (ToggleButton)findViewById(R.id.toggleButton);
tgButton.setChecked(mBool);
final boolean mBool1 = servicePrefs.getBoolean("myservice", false);
final Boolean c = mBool1;
Log.e("Update pref", c.toString());
tgButton=(ToggleButton)findViewById(R.id.toggleButton);
tgButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(tgButton.isChecked())
{
startService(new Intent(Toggle_Activity.this , MyService.class));
System.out.println("Service is started in togglr button");
}
else
{
stopService(new Intent(Toggle_Activity.this,MyService.class));
System.out.println("Service is stopped in togglr button");
}
}
});
}
}

in the first activity, you'd put startService(new Intent(this, MyService.class)) in onresume
from oncreate

I figured this out the best way possible. I basically linked my toggle button and my service together using a shared preference and listeners. I called this shared preference "service_running" and then implemented my listeners in the activity onCreate() method the toggle button is present in (in this case, MainActivity.
In my onCreate() heres what I did:
// set toggle button based on service running
final ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton);
toggle.setChecked(serviceRunning(SendService.class));
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startSendService();
}
else {
stopSendService();
}
}
});
// set shared pref listener for toggle
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("service_running")) {
toggle.setChecked(prefs.getBoolean("service_running", false));
}
}
};
prefs.registerOnSharedPreferenceChangeListener(myPrefListner);
startSendService() and stopSendService() simply start or stop my service depending on if it is running and has the correct app permissions or not.
Heres the method which checks if a service is running (credit to #geekQ in this thread):
private boolean serviceRunning (Class<?> serviceClass) {
// check if a service class is currently running
ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
And then in my service, in the onStartCommand() I just changed the shared preference to true, and in the onDestroy() I changed it to false.
The only caveat with this is that you have to hide this shared preference from your preference screen, which can be done with:
getPreferenceScreen().removePreference(findPreference("service_running"));

Related

setText in app when GPS enabled/disabled in device

I'm using the following code to change two text views based on when the user turns on/off their network and their GPS. I was able to get the network text view to work but not the location text view. I think I am using the wrong filter, but I don't know which to use instead. Any suggestions/answers?
public class MainActivity extends AppCompatActivity {
TextView networkTextView;
TextView locationTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
networkTextView = findViewById(R.id.networkTextView);
locationTextView = findViewById(R.id.locationTextView);
IntentFilter filter1 = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver1, filter1);
IntentFilter filter2 = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
registerReceiver(broadcastReceiver2, filter2);
}
BroadcastReceiver broadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noNetworkConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noNetworkConnectivity) {
networkTextView.setText("Disconnected");
} else {
networkTextView.setText("Connected");
}
}
}
};
BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
boolean noLocationConnectivity = intent.getBooleanExtra(LocationManager.PROVIDERS_CHANGED_ACTION, false);
if (noLocationConnectivity) {
locationTextView.setText("Disconnected");
} else {
locationTextView.setText("Connected");
}
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver1);
unregisterReceiver(broadcastReceiver2);
}
}
Update:
In the broadcast receiver for the location I replaced
boolean noLocationConnectivity = intent.getBooleanExtra(LocationManager.PROVIDERS_CHANGED_ACTION, false);
with
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean locationConnectivity = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
but that didn't work. Maybe need to request location data permission from user?
Update 2:
Realized that it is registering boolean changes of the LocationManager.GPS_provider, but not initially. Only after the Location setting is manually changed after the app is started does the text change, unlike with the network check that changes the text as soon as the app starts.
I think that this question has already been answered here
But I'm thinking if use LocationManager and LocationListener is a good idea or not, I mean, LocationListener has those overrided methods:
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
I leave it to your consideration

Background service isn't working properly

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

Handler doesn't stop on button click

I have a runnable which starts an activity and a handler, which lets the runnable repeat after 5 seconds. However, i implemented a "stop button" which should stop that handler, but somehow it doesn't work.
I would appreciate some help why it doesn't stop the loop.
public class MainActivity extends Activity {
private Button callBtn;
private Button stopBtn;
Handler handler = new Handler();
Runnable redial=new Runnable(){
#Override public void run(){Intent callIntent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:+49888888"));startActivity(callIntent);
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callBtn = (Button) findViewById(R.id.call);
stopBtn = (Button) findViewById(R.id.stop);
// add PhoneStateListener for monitoring
MyPhoneListener phoneListener = new MyPhoneListener();
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
// receive notifications of telephony state changes
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
callBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
redial.run();
}
});
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(redial);
}
});
}
private class MyPhoneListener extends PhoneStateListener {
private boolean onCall = false;
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
// phone ringing...
Toast.makeText(MainActivity.this, incomingNumber + " calls you",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// one call exists that is dialing, active, or on hold
Toast.makeText(MainActivity.this, "on call...",
Toast.LENGTH_LONG).show();
//because user answers the incoming call
onCall = true;
break;
case TelephonyManager.CALL_STATE_IDLE:
// in initialization of the class and at the end of phone call
// detect flag from CALL_STATE_OFFHOOK
if (onCall == true) {
Toast.makeText(MainActivity.this, "restart app after call",
Toast.LENGTH_LONG).show();
// restart our application
Intent restart = getBaseContext().getPackageManager().
getLaunchIntentForPackage(getBaseContext().getPackageName());
restart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(restart);
onCall = false;
handler.postDelayed(redial, 5000);
}
break;
default:
break;
}
}
}

How to set the android app theme in java,

I want to allow the user change the theme from the entire app by clicking a button,
So I want to know if there is a way to change the app theme within java code.
You can use the setTheme() method on a Context.
Be sure to pay attention to the note in the documentation- you need to call setTheme() before you instantiate any Views.
If you change themes while your application is open, you will need to recreate your Activity for the changes to show.
public class ThemeSwitcher extends Activity implements OnClickListener {
private boolean isThemeSwitch = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (isDefault() == false) {// Default theme defined in Style file.
setTheme(android.R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.theme_switcher);
findViewById(R.id.switchTheme).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.switchTheme) {
switchTheme();
isThemeSwitch = true;
finish();
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isThemeSwitch) {
Intent intent = new Intent(this, ThemeSwitcher.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
private SharedPreferences getPreference() {
return getSharedPreferences("theme", 0);
}
private void switchTheme() {
if (isDefault()) {
getPreference().edit().putBoolean("theme", false).commit();
}
else {
getPreference().edit().putBoolean("theme", true).commit();
}
}
private boolean isDefault() {
boolean isDef = true;
isDef = getPreference().getBoolean("theme", false);
return isDef;
}
}

Android Service ("startService & stopService") and Play/Stop Button in One

I am developing an Android app and I need to make one button which will be a Play/Stop button for Android Service playing and stopping.
Play button is for startActivity();
Stop button is for stopActivity();
How do I make this?
You just need to declare a flag variable and declare body of onclick() based on flag value like this.
public class ServiceActivity extends Activity {
Button play;
int button_status=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play=(Button)findViewById(R.id.button1);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(button_status == 1)//play the service
{
button_status=0;
Intent i=new Intent(ServiceActivity.this,Playing.class);
startService(i);
}
else//stop the service
{
button_status=1;
Intent i=new Intent(ServiceActivity.this,Playing.class);
stopService(i);
}
});
}
}
or you can use ToggleButton for your purose.
boolean isStop = false;
public void startorStop() {
if(isStop) {
// play it
} else {
//stop it
}
isStop = !isStop;
}
Just use a boolean to remember if it's on or off and toggle it
boolean isOn = false;
public void startStopButton() {
if(isOn) {
stopActivity();
isOn = false;
} else {
startActivity();
isOn = true;
}
}
Now whenever your button is pressed, you can call this method.

Categories

Resources