show a custom message every 10 second from background service - java

I want to implement a feature in my application to show a custom message after every 10-20 second also when app is not started and phone is in wake up state...
I am sharing you a screenshot and a refer app which has this functionality in their app I want same functionality in my app.
App name is Auto- Athkar for muslims

An android toast could work in a while loop?
Your have to register when the app is pushed minimised which is normally done by
public void onPause () {
}
You'd have to start a service in your Application class to run it constantly. Even if user force closes then it should run.
Create your own service class :
public class Servicey extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int begin(Intent intent, int flags, int beginId) {
// do that shiny stuff with toasts
return super.begin(intent, flags, beginId);
}
Then start your service on the onCreate() of your activity
startService(new Intent(this, Servicey.class));

Related

android service stops when main activity is destroyed

I am making an app that gives the user a notification when it is time for a monster egg to be hatched again. Up to 10 eggs can be hatched per day every 5 minutes. I thought I'd make a service that keeps a track of how much time has passed, but every time MainActivity closes on the emulator the service stops and calls onDestroy(). I made a test service to see if I could get the service to display log messages, or do something when onDestroy() is called. I was able to get the service to run a thread in onDestroy(), but obviously this is dangerous if I were to implement it.
I was also reading around the site and notice people recommend either Handler or Alarm Manager. Should I use these instead of service? And could someone also explain why my service stops when MainActivity is destroyed? Also would it be recommended to retrieve/store data from app preferences within this service or whatever class I end up using so that the service and MainActivity can talk to each other? Like for example a seed based on whenever the timer is up so that MainActivity can create an egg from the seed whenever it is started?
(edit)oops almost forgot: I also need it so that notifications appear whenever an egg is ready to hatch and whenever another batch of eggs is ready for the day. Whenever the user starts the app, the app should also display how long is left for another egg or another batch if the user has already used up their eggs for the day. Figured this context was important in determining whether I should use a service, alarm manager, or handler.
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class egg_notifications extends Service {
public static int time = -1;
public egg_notifications() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AsyncTask datatask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
for(int c=0;c<300;c++){
Log.i("d","Time is "+c);
try {
Thread.sleep(1000);
} catch (Exception e) { }
}
return null;
}
}.execute();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
Log.i("d","Service onDestroy");
AsyncTask datatask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
for(int c=0;c<300;c++){
Log.i("d","Time is "+c);
try {
Thread.sleep(1000);
} catch (Exception e) { }
}
return null;
}
}.execute();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Services end after 2 minutes in modern Android. If you just need a 5 minute timer, use an Alarm and AlarmManager to set one.

Listening to volume button events android

I saw this topic
Listen to volume buttons in background service?
and know the way to listenting to volume keys in background service is to detect the amount of system volume(or music...) and see if it decrease or increase we can detect buttons
i see an app that detects pressing volume up/down button together in locked mode or screen off and it is using AccessibilityService. how it is possible?
https://play.google.com/store/apps/details?id=in.blogspot.anselmbros.torchie&hl=en
You can create BroadcastReceiver inside Service.
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
final BroadcastReceiver vReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//your code here
}
};
registerReceiver(vReceiver, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));
}
}
Or playing media with 0 volume in background and then the key will be always listened by Reciever with MediaButtonIntent as shown in this GitHub sample

make unity run in background on android

I want to make mygame (unity) run in background on android when I click a button.
There is the information that i need to set up plugin and use service so I connected plugin between unity and android and made a button on unity.
When the button is clicked , the onCreate method should be activated and the service should be activated.
But i have no idea what to do next. There is no paper to make whole unity game run in background. there is only about the way how to deliver the string like "a, b, c , 1, 2,3" .
according to the docs, i need to use the method called " unitysendmessage()" .but if i use it i can't make methods on unity as service. it just sends strings.
is there any solution to make unity run in background ?
Button on unity
public void andro() {
_plugins.Call("onCreate");
}
Android code
public class MainActivity extends UnityPlayerActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, my.class));
}
}
public class my extends Service {
public int onStartCommand(Intent intent, int flags, int startld) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

How to display a toast message in only one activity?

In an application I am developing I have some code that attempts to submit information to the internet. If the connection can not be made, I pop up a toast message instructing the user to check the network connection.
Toast.makeText(getApplicationContext(), "Check network connection.", Toast.LENGTH_SHORT).show();
The problem I have is the toast message comes up no matter what the user is looking at! Even if the user is in a different app and my app is running in the background! This is not the desired behavior as I send a notification to the user if network activity fails. I only want the toast message to appear if the user is in the activity that is generating the network activity. Is there a way to do this?
If this is not possible my idea was to just put some kind of visual element in my activity - rather than display a toast message.
Thank You!
You can use a boolean class member in order to keep track of activity state changes.
public class YourClass extends Activity {
private boolean mIsResumed = false;
#Override
public void onResume() {
super.onResume();
mIsResumed = true;
}
#Override
public void onPause() {
super.onPause();
mIsResumed = false;
}
public boolean isResumed() {
return mIsResumed;
}
}
Then you can use something like this:
if (isResumed()) {
//show Toast
}
Use a dynamic BroadcastReceiver. Your background service will broadcast an Intent when something happens. All of your app's activities will register a dynamic BroadcastReceiver which will listen for these events. When such event occurs it will show a toast. When none of your activities are running nothing will happen.
Inside your service
public static final ACTION_SOMETHING = BuildConfig.APPLICATION_ID + ".ACTION_SOMETHING";
public void doSomething() {
// ...
// Show toast if app is running. Or let the app react however you please.
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(ACTION_SOMETHING));
// ...
}
Of course you can put additional information in the Intent as extras and access them in the BroadcastReceiver.
Inside your activities
private final IntentFilter onSomethingIntentFilter = new IntentFilter(MyService.ACTION_SOMETHING);
private final BroadcastReceiver onSomething = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// This check seems redundant but it's not. Google it.
if (MyService.ACTION_SOMETHING.equals(intent.getAction()) {
// Show toast here.
}
}
};
public void onResume() {
super.onResume();
// Start listening for events when activity is in foreground.
LocalBroadcastManager.getInstance(this).registerReceiver(onSomething, onSomethingIntentFilter);
}
public void onPause() {
super.onPause();
// Stop listening as soon as activity leaves foreground.
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onSomething);
} catch (IllegalArgumentException ex) {}
}
You may want to pull this code to a common activity parent, a BaseActivity, so you don't repeat yourself.
This is a common case of Provider-Subscriber pattern. Another implementation would be an EventBus.
Keeping it simple, try adding a boolean flag in Activity and set its value as true in onResume & false in onPause. Then display the toast if the boolean flag is true.

I want to create a global MediaPlayer that will keep playing no matter which layout is displayed

Instead of creating one in my menu class, I'd like to create a global one outside of the menu class that I can call to keep the sound playing no matter which activity is started. I'm a noob to java, but I have searched and can't find a solution. Here is my "menu" activity. As you can see my MediaPlayer snd is local so it gets paused when the onPause method gets called.
public class Menu extends Activity{
MediaPlayer snd;
ToggleButton btnSound;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
snd = MediaPlayer.create(getApplicationContext(), R.raw.bgmusic);
snd.start();
btnSound = (ToggleButton) findViewById(R.id.tglSound);
#Override
protected void onPause() {
super.onPause();
snd.pause();
}
The best way to implement your requirement is using a service. You can start a service while the app is intialised. Inside the service start a mediaplayer and start playing. So evenif you are navigating to next or other activities the media will keep playing. You can also give property to the service when to start ad stop. Isted of pausing or stoping mediaplayer you can just stop the service so that the mediplayer will also stop playing. Hope this link will help you for sure.
The answer to your problem lies in the Android reference:
MediaPlayback
If you want your media to play in the background even when your
application is not onscreen—that is, you want it to continue playing
while the user is interacting with other applications—then you must
start a Service and control the MediaPlayer instance from there. You
should be careful about this setup, because the user and the system
have expectations about how an application running a background
service should interact with the rest of the system. If your
application does not fulfil those expectations, the user may have a
bad experience. This section describes the main issues that you should
be aware of and offers suggestions about how to approach them.
Create a service like this snippet:
public class whatEverYourServiceName extends Service{
#Override
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
//Add your code here mate
}
#Override
public void onDestroy(){
super.onDestroy();
//Add what do you want to do here when the service is stop like do a backflip
snd.pause();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Then call it using this
Intent it = new Intent();
it.setAction("your.package.name.whatEverYourServiceName");
startService(it);
Then add this to your manifest
<service
android:name="your.package.name.whatEverYourServiceName"
android:label="Your Service Homie"
android:process=":my_process" >
<intent-filter>
<action android:name="your.package.name.whatEverYourServiceName" >
</action>
</intent-filter>
</service>
To stop the sound just stop the service using this
stopService(new Intent(this, whatEverYourServiceName.class));
Hope it helps.

Categories

Resources