In Override, I get a "Method does not override method from its super class" error. I also get "onResume cannot resolve method" error in super.onResume ();
It was working on MainActivity but when I move the code to Service class, I got this error.
As you can see:
public class Servis extends Service implements SensorEventListener{
SensorManager mgr;
Sensor temp;
TextView text;
StringBuilder msg = new StringBuilder(2048);
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(Servis.this, R.raw.warning);
mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
temp = mgr.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); }
#Override
protected void onResume() {
mgr.registerListener(this, temp, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
#Override
protected void onPause() {
mgr.unregisterListener(this, temp);
super.onPause();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
float fahrenheit = event.values[0] * 9 / 5 + 32;
if(fahrenheit < 68)
mediaPlayer.start();
}
}
A Service is not an Activity, that's why these methods cannot be overridden. You can safely remove them and instead have to let the Activity implement them. When a Service implements SensorEventListener, this would look alike this:
public class Servis extends Service implements SensorEventListener {
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
}
#Override
public void onDestroy() {
}
#Override
public IBinder onBind(Intent intent) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
}
}
As noted above, Services class does not include the methods you so there is no override to be performed. Refer to Service documentation
The closes method you might want to consider it to override
onStart(Intent intent, int startId)
It's perhaps the closest to OnResume
Related
I'm using the BackgroundSoundService for playing music in a background of my activity. However, when I switch to another activity, I would like to use another sound.
This is how my class looks like. I need to change that "R.raw.sound" programmatically.
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return startId;
}
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}}
I'm new to android, and working on a project where I have to implement background music in our app. I've already implemented background music using service, the problem is: I don't know how to change the volume of the music dynamically using a seekbar from an activity.
My service looks like this:
package hu.szoftverprojekt.holdemfree.controller;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import androidx.annotation.Nullable;
import hu.szoftverprojekt.holdemfree.R;
public class PlaySound extends Service {
MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player=MediaPlayer.create(this, R.raw.ss);
player.setLooping(true);
player.start();
player.setVolume(SettingsScreen.volume, SettingsScreen.volume);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
Well once you have the SeekBar and the OnSeekBarChangeListener being called as you change the SeekBar, the next major thing is communicating this from your activity to your service this change.
Have a look at the android docs Creating a bound service for the offical way to communicate between an Activity and Service using no 3rd party libraries.
HOWEVER
You could also use a 3rd party library like EventBus (which I'd recommend as it's much easier to use and implement in my opinion).
Here is an example using EventBus:
build.gradle:
dependencies {
implementation 'org.greenrobot:eventbus:3.2.0'
}
MediaVolumeEvent.java:
public class MediaVolumeEvent {
private int volume;
public MediaVolumeEvent(int volume) {
this.volume = volume;
}
public int getVolume() {
return volume;
}
}
PlaySound.java:
public class PlaySound extends Service {
#Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
#Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
player.stop();
super.onDestroy();
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MediaVolumeEvent event){
player.setVolume(event.getVolume(), event.getVolume());
}
}
In your activity inside the OnSeekBarChangeListener:
SeekBar seekBar= (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
EventBus.getDefault().post(new MediaVolumeEvent(progress));
}
});
I have a service which has an interface, I'm implementing the interface callback in multiple activities, but because of I'm calling the app instance on every activity's onCreate, the interfaces are responding on the current activity only. How do I make sure they work all together in every activity.
MyApp.java
public class MyApp extends Application {
private static MyApp myApp;
#Override
public void onCreate() {
super.onCreate();
myApp = new MyApp();
}
#Contract(pure = true)
public static synchronized MyApp getInstance() {
MyApp myApp;
synchronized (MyApp.class) {
myApp = MyApp.myApp;
}
return myApp;
}
public void setCallBackListener(MyService.ReceiversCallbacks receiversCallbacks) {
MyService.receiversCallbacks = receiversCallbacks;
}
}
MyService.java
public class MyService extends Service {
public static MyService.ReceiversCallbacks receiversCallbacks;
public MyService() {
super();
}
public interface ReceiversCallbacks {
void onReceiveCallbacks(String data);
}
#Override
public void onCreate() {
super.onCreate();
Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_ID)
.setContentTitle("Background service")
.setSmallIcon(R.drawable.ic_launcher)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (MY_LOGIC) receiversCallbacks.onReceiveCallbacks("DATA_FROM_MY_LOGIC");
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
ActivityA.java
public class ActivityA extends AppCompatActivity implements MyService.ReceiversCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
#Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
ActivityB.java
public class ActivityB extends AppCompatActivity implements MyService.ReceiversCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
#Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
Each activity's onCreate when I do this MyApp.getInstance().setCallBackListener(this); The focus of the call back shifts to the new activity. But I want the focus in both or more activities at the same time, how do I do that? Is there any better way for the solution I want?
Please note these:
I don't want to call those functions onResume
I don't want to use Broadcasts
I just created different interfaces for each activity and registered them to their corresponding activity, and they worked!
MyApp.getInstance().setCallBackListener(this);
In my Android app I have two activities :
1) MapsActivity
2) OtherActivity
MapsActivity has navigation drawer through which I opened OtherActivity . Now , I want to call a method (like updatemap() ) from MapsActivity .
After searching a lot on google I found this question on stackoverflow
How to call method in main activity from other activity? but that doesn't solves my problem .
UPDATE :
Here is the code for OtherActivity :
public class OtherActivity extends AppCompatActivity {
#Override
protected void attachBaseContext(Context newBase) {.....}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.... }
#Override
protected void onStart() {
super.onStart();
removeConnection(userID)
.... }
private void removeConnection(String currentUserId) {
...
// Here I want to call a function from MapsActivity i.e. disaplayLocation()
}
public static class ConnectedViewHolder extends
RecyclerView.ViewHolder{ ... }
}
Code for MapsActivity is :
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
#Override
protected void attachBaseContext(Context newBase) { ... }
#Override
protected void onCreate(Bundle savedInstanceState) { ... }
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) { ... }
private void setUpLocation() { ... }
public void displayLocation() { ... } // This is the function i want to call
private void createLocationRequest() { ... }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { ... }
protected synchronized void buildGoogleApiClient() { ... }
private boolean checkPlayServices() { ... }
private void requestRuntimePermission() { ... }
private void startLocationUpdates() { ... }
#Override
public void onMapReady(GoogleMap googleMap) { ... }
#Override
public void onConnected(#Nullable Bundle bundle) { ... }
#Override
public void onConnectionSuspended(int i) { ... }
#Override
public void onConnectionFailed(#NonNull ConnectionResult
connectionResult) { ... }
#Override
public void onLocationChanged(Location location) { ... }
#Override
public boolean onCreateOptionsMenu(Menu menu) { ... }
#Override
public boolean onOptionsItemSelected(MenuItem item) { ... }
private void makeConnectionToGetLocation() { ... }
private void updateConnectedLatLng() { ... }
}
I am pasting only structure of code because it is 1000 line of code and pasting here is of no use and become more complicate to read .
I tried to add static keyword before displayLocation method but it gives error in variables within function and making every variable to global is not possible .
If MapsActivity is expecting a result from OtherActivity, you're better off with Getting Result From an Activity. Simply call OtherActivity via startActivityForResult() (instead of startActivity()):
static final int MAP_REQUEST = 1; // your request code
...
private void callOtherActivity() {
Intent intent = new Intent(this, OtherActivity.class)
startActivityForResult(intent, MAP_REQUEST);
}
Then in your MapsActivity, do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAP_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
updateMap();
}
}
}
Make a static function in one Activity like
public static double getVariance(double[] data)
{
double mean = getMean(data);
double temp = 0;
for(double a :data)
temp += (mean-a)*(mean-a);
return temp/data.length;
}
Then in another activity call it as:
double res = Activity1.getVariance(<your data>);
Hope it helps.
Be aware, you may get NullObjectRefernce if the other activity is closed.
to do it you can use public static method. so, you can call it from anywhere in the application.
in your activity add it.
public static void YOUR_NAME(){}
to call it in second activity add it.
try{
YOUR_ACTIVITY.YOUR_NAME();
}catch(Exception e){}
another solution, you can use EventBus library
https://github.com/greenrobot/EventBus
I made a service that play background music, but when the music finished I want to replay it again. Which method can I use in my service?
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Just use MediaPlayer.setLooping() method.
Sample code:
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setVolume(100,100);
player.setLooping(true);
}
Set OnCompletionListener via setOnCompletionListener. And it he callback you can start it again.