I don't want to use AudioManager... Using the MediaPlayer API, my app
is not able to set the volume to desired level.
As it playes on previous level of volume which is set by Volume UP and Volume Down Key.
public class MainActivity extends AppCompatActivity {
protected static MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button next=(Button) findViewById(R.id.button);
mp=MediaPlayer.create(this,R.raw.m1);
mp.setVolume(0.02f,0.02f);
mp.start();
mp.setLooping(true);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
As mentioned in documentation:
"This API is recommended for balancing the output of audio streams within an application. Unless you are writing an application to control user settings, this API should be used in preference to setStreamVolume(int, int, int) which sets the volume of ALL streams of a particular type. "
https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float,%20float)
You can however set a stream to your mediaplayer and let is play on
the desired stream like Music / Notification or Alarm which should
suffice the req.
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
Otherwise if you want to play some sound with certain level you have to use AudioManager API's to set a certain stream & set the volume of the stream and play the audio. This is a common practice.
I have a single activity timer application in which I have overridden the onPause() method to pause the timer when the user presses the home or back button. However, I would like the timer to keep moving in the case that the user manually turns off his screen, but I know this will also call the onPause() method. Is there any way to get around this?
You can override onBackPressed to allow you to put some extra logic when the back button is pressed. However, a better approach might be to put your code in onStop(), which is only called when another Activity is moved to the foreground.
See the Android Docs for more detail
I ended up doing this by detecting and ignoring a screen turn off event inside the onPause() method. Instructions on how to do this can be found here: http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
Specifically, I used this code from the comments (courtesy of Kyle):
#Override
protected void onCreate() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
//NEW
PowerManager pm =(PowerManager) getSystemService(Context.POWER_SERVICE);
// your code
}
#Override
protected void onPause() {
// when the screen is about to turn off
// Use the PowerManager to see if the screen is turning off
if (pm.isScreenOn() == false) {
// this is the case when onPause() is called by the system due to the screen turning off
System.out.println(“SCREEN TURNED OFF”);
} else {
// this is when onPause() is called when the screen has not turned off
}
super.onPause();
}
I have this code that allows me to press a button to turn on my phones flashlight. What would be the best way to keep the light on, while the application is closed? I heard asynctask is good, but I read that it's meant for a background task that will communicate with the UI. What kind of "thread" should I use for this type of "application".
My onClickListener code:
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//If Flag is set to true
if (isFlashOn) {
Log.i("info", "torch is turned off!");
//Set the flashmode to off
p.setFlashMode(Parameters.FLASH_MODE_OFF);
//Pass the parameter ti camera object
camera.setParameters(p);
//Set flag to false
isFlashOn = false;
//Set the button text to Torcn-ON
button.setText("Torch-ON");
}
//If Flag is set to false
else {
Log.i("info", "torch is turned on!");
//Set the flashmode to on
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
//Pass the parameter ti camera object
camera.setParameters(p);
//Set flag to true
isFlashOn = true;
//Set the button text to Torcn-OFF
button.setText("Torch-OFF");
}
}});
}
Sounds that you need a service
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use
I want to write an android app that would be a background service that would listen for either a specific gesture or key press in the and then trigger an action. Is it even possible to do such a thing with a service? If so could someone guide me the right direction. I have search high and low can could seem to find an answer.
not hard to read where they touch, but the touches in this way provide only location, not time, not on ups or downs.
in your service
#Override
public void onDestroy() {
super.onDestroy();
if (layout != null) {
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(layout);
layout = null;
}
}
#Override
public void onCreate() {
super.onCreate();
layout = new RelativeLayout(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.setTitle("test");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(layout, params);
}
and for your touch handler, it will have to be as
public boolean gestureHandler(MotionEvent event, boolean eat) {
if(event.getAction() == MotionEvent.ACTION_OUTSIDE)
Doing this (except on top of apps that cooperate by sending you their input) would be a huge security hole of the kind that the android architecture is designed to prohibit. To do it you would need to modify the platform and have the watching done by something running with access to the raw touch and button input, possibly as part of the driver for that.
In other words you can with difficulty do it on your own rooted phone or on devices you manufacture, but it's not usable for most people.
On pressing the back button, I'd like my application to go into the stopped state, rather than the destroyed state.
In the Android docs it states:
...not all activities have the behavior that they are destroyed when BACK is pressed. When the user starts playing music in the Music application and then presses BACK, the application overrides the normal back behavior, preventing the player activity from being destroyed, and continues playing music, even though its activity is no longer visible
How do I replicate this functionality in my own application?
I think there must be three possibilities...
Capture the back button press (as below) and then call whatever method(s) the home button calls.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
Capture the back button press and then spoof a home button press.
Capture the back button press, then start an Activity of the home screen, effectively putting my application's Activity into the stopped state.
Edit:
I know about services and am using one in the application to which this problem is related. This question is specifically about putting the Activity into the stopped state rather than the destroyed state on pressing the back button.
Most of the time you need to create a Service to perform something in the background, and your visible Activity simply controls this Service. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activity can finish as usual and the Service will still be running.
A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:
// 2.0 and above
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
// Before 2.0
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack can be used as a quick alternative on occasion.
NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button.
Use the following code:
public void onBackPressed() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.
However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:
A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.
These seems appropriate for your requirements.
try to override void onBackPressed() defined in android.app.Activity class.
if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works
#Override
public void onBackPressed() {
// check if page 2 is open
RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
if(page2layout.getVisibility() == View.VISIBLE){
togglePageLayout(); // my method to toggle the views
return;
}else{
super.onBackPressed(); // allows standard use of backbutton for page 1
}
}
hope it helps someone,
cheers
Working example..
Make sure don't call super.onBackPressed();
#Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
In this way your Back Button act like Home button . It doesn't finishes your activity but take it to background
Second way is to call moveTaskToBack(true); in onBackPressed and be sure to remove super.onBackPressed
Even better, how about OnPause():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().
When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure toenter code here not do anything lengthy here.
This callback is mostly used for saving any persistent state the activity is editing and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one.
This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.
Override onBackPressed() after android 2.0.
Such as
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
I have use #Mirko N. answser using made the new Custom EditText
public class EditViewCustom extends EditText {
Button cancelBtn;
RelativeLayout titleReleLayout;
public EditViewCustom(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EditViewCustom(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditViewCustom(Context context) {
super(context);
}
public void setViews(Button cancelBtn,RelativeLayout titleReleLayout){
this.cancelBtn = cancelBtn;
this.titleReleLayout = titleReleLayout;
}
#Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.d("KEYCODE_BACK","KEYCODE_BACK");
cancelBtn.setVisibility(View.GONE);
this.setFocusableInTouchMode(false);
this.setFocusable(false);
titleReleLayout.setVisibility(View.VISIBLE);
return super.onKeyPreIme(keyCode, event);
}
return super.onKeyPreIme(keyCode, event);
}
}
Then set data from your activity
searchEditView.setViews(cancelBtn, titleRelativeLayout);
Thank you.
I've tried all the above solutions, but none of them worked for me. The following code helped me, when trying to return to MainActivity in a way that onCreate gets called:
Intent.FLAG_ACTIVITY_CLEAR_TOP is the key.
#Override
public void onBackPressed() {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}