I am making a simple scare your friend app. You have to press a button and then set a minute timer that will then bring up classic exorsist icon and scream on screen. I tried putting android:persistent="true", but it didn't work...
Here's my activity:
package com.odysseus.myapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer scareMusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startTimer = (Button) findViewById(R.id.btimerStart);
scareMusic = MediaPlayer.create(MainActivity.this, R.raw.monster_scream);
startTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread scareTimer = new Thread(){
public void run(){
try{
sleep(5000);
Intent activityIntent = new Intent("com.odysseus.myapp.SCARER");
startActivity(activityIntent);
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
scareTimer.start();
}
});
}
}
I am really new to android so don't just say use a service or something because I don't know what that is. Other answers I found were too advanced for me so please explain as much as you can!
There's no way to truly make your app immune to shutdown. The attribute "android:persistent" gets ignored for all apps that are not System apps.
That being said, to make sure that the application fires the intent after the given time, you'll probably have to place the launching code in a serivce (if even possible then).
Instead of using Activity you can use a Service that always run in the background. See this answer for how to create a app that just has an activity. Android app with Service only. As an work around you can create an Activity no content view or transparent layout, then in this activity start the service and then quickly close the activity using finish().
Now in the Service you can use the exact code that you are trying to use in an Activity. But remember to stop the Service after showing com.odysseus.myapp.SCARER.
Update :-
In your com.odysseus.myapp.SCARER activity after showing the code you can use the following command to stop the Service.
stopService(new Intent(this, service.class));
To use services is not really hard. Just create a new class and add extends Service. When you're done doing that you should add this method:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Your code here
return START_STICKY;
}
Inside this method you can launch your media player. To stop the service you just put stopSelf() in the onDestroy(). Good luck!
Related
I'm trying to develop a game app. At the gameover screen, I want to have a button that goes back to the start when you click it. But the problem is, it doesn't work. I really don't know why it doesn't work, I have tried everything but can't find the problem. Can someone help me?
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class GameOver extends AppCompatActivity {
MediaPlayer gameoversound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
Button weiter_button = (Button) findViewById(R.id.weiter);
weiter_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { goToMainActivity(); }
});
}
private void goToMainActivity() {
Intent back = new Intent( this, MainActivity.class);
startActivity(back);
}
}
Change this to GameOver.this
You don't have to cast widgets explicitly anymore, except for some special cases. It has been this way for a while.
If the game is over, you'd best insert a finish(); after launching the main Activity. You don't want users to be able to go back to the gameover screen by pressing the back button.
Set up FLAGS for your Intents. This comes in handy because if you didn't finish(); some Activity it remains in the stack, so it will be launching that one, but then you might want a new one. This will cause issues in navigation.
Add/ check your onBackPressed() methods for the 2 Activities.
Furthermore, specify that you are overriding the method
#Override
public void onClick(View view)
{
}
In the XML, <Button> tag, add
android:clickable=true
android:focusable=true
I'm trying to create a game log, to show what happened on each round of the game. The log is in another activity but I want to be updated constantly with whatever the player does. A player just presses buttons that do certain things. It's too much code to post, but I have made a new bundle, and an intent.
In MainActivity.
Bundle bundle = new Bundle();
Intent GameLogSwitch = new Intent(getApplicationContext(),GameLog.class);
I am trying to put this to send to the other activity but I don't know if you can put variables in it. otherwise it works with simple words such as ("key","It works")
GameLogSwitch.putExtra("Break","---BREAK---"+"\n"+Player1Name+": "+GreenResult.getText()+"("+GrTop1+","+GrTop2+","+GrTop3+")"+"\n"+Player2Name+": "+RedResult.getText()+"("+RdTop1+","+RdTop2+","+RdTop3+")");
and then of course I have this when the gamelog button is pressed
startActivity(GameLogSwitch);
Now in Gamelog.class i have this.
package com.example.adam.snookerproject;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class GameLog extends AppCompatActivity {
private TextView GameLogText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_log);
GameLogText = (TextView) findViewById(R.id.GameLogText);
Intent GameLogSwitch = getIntent();
String myString = GameLogSwitch.getStringExtra("Break");
GameLogText.append(myString);
}
}
I have a couple of questions. First, why does append only work once with my string when I start the activity i.e when I go back and press the same button again it won't write the same thing again underneath?
Secondly, it doesn't seem to work for my "Break" key, does this have to do with the fact that there are variables in the text I'm sending? It only works for simple text like GameLogSwitch.putExtra("key","It works");
There must be an easier way to do this! Thank you.
UPDATE 1: The answer from Drv does seem to work, but when I try to do GameLogText.append(AppConstants.log) it just replaces everything in the textview no matter how many times I press the button. I think the activity is just resetting each time I start it again. Any way around this?
Make a global string in Constants class and use it wherever you want:
public class AppConstants{
public static String log="";
}
Edit the string in the class where you are sending it in intent:
AppConstants.log="---BREAK---"+"\n"+Player1Name+": "+GreenResult.getText()+"("+GrTop1+","+GrTop2+","+GrTop3+")"+"\n"+Player2Name+": "+RedResult.getText()+"("+RdTop1+","+RdTop2+","+RdTop3+")";
And use it in your class as:
package com.example.adam.snookerproject;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class GameLog extends AppCompatActivity {
private TextView GameLogText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_log);
GameLogText = (TextView) findViewById(R.id.GameLogText);
//get your log here using AppConstants.log
}
}
Try to use getContext() instead of getApplicationContext, then check your string in debug mode
Use Callback or Interface. Fire the Interface from the Main Activity and Implement the call Interface in the Activity where you want the Textview to be Updated. Inside that method Update your Text View.
Read here More about Communication between Activity Activity and Fragment Activity
(Posted solution on behalf of the OP).
I managed to append using "\n"+AppConstants.log at the end of each output.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my application I noticed these three things:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The problem is I don't want the user to click on Back at a certain point in my application. I don't want to disable the back button completely in my application, only when one intent is called. How can I do that?
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my application, some of the toast notifications are residual and are popping outside of my application. Is there a reason for that? Did I miss something in the activity lifecycle to handle the cancellation of toasts at a certain point?
Lastly, this one is rather tough to solve. How do I lock my screen so that when the user rotates the device, that the activity doesn't not get called again and the asynctask can still resume without starting over again?
Thanks a lot for your time. Just curious why these things happen and what should I look into?
Here's my code:
//Main Activity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.*;
public class MainActivity extends Activity {
//fields
private ProgressDialog progressBar;
private Context context;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;
//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Executes the AsyncTask
new RetrieveInfoTask().execute();
//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public class RetrieveInfoTask extends AsyncTask<Void, Void, Void> {
//Called on the UI thread to execute progress bar
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage(MainActivity.this.getString(R.string.retrieve_info));
progressBar.show();
}
//Methods that retrieves information from the user device. This is performed in the Background thread
private void retrieveInfo() {
try {
//Reading the drawable resource line by line
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//doInBackground calls retrieveInfo() to perform action in Background
#Override
protected Void doInBackground(Void... params) {
retrieveInfo();
return null;
}
//When the background task is done, dismiss the progress bar
#Override
protected void onPostExecute(Void result) {
if (progressBar!=null) {
progressBar.dismiss();
}
}
}
}
//RetrieveInfoActivity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class RetrieveInfoActivity extends Activity {
private static String TAG = "RetrieveInfoActivity";
private Context context;
String fileLastSync = "09-18-2014 03:47 PM";
#Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieve_info);
//Once the new activity is launched, the setup is complete
Toast.makeText(getApplicationContext(), "Setup Complete!",
Toast.LENGTH_LONG).show();
//Gets the 'last synced' string and sets to datetime of the last sync
Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
//calls registerReceiver to receive the broadcast for the state of battery
this.registerReceiver(this.mBatInfoReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
//Battery level
int level = intent.getIntExtra("level", 0);
//Dynamically sets the value of the battery level
TextView batteryTextView = ((TextView) findViewById(R.id.battery) );
batteryTextView.setText("Battery Level: " + String.valueOf(level)+ "%");
//If the battery level drops below 25%, then announce the battery is low
//TODO: Add 25 to constants file.
if(level < 25) {
Toast.makeText(getApplicationContext(), "Low Battery!",
Toast.LENGTH_LONG).show();
}
//Plugged in Status
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//Battery Status
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//If the device is charging or contains a full status, it's charging
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
//If the device isCharging and plugged in, then show that the battery is charging
if(isCharging && plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Charging.." + String.valueOf(level)+ "%",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unplugged!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(this.mBatInfoReceiver);
}
catch (Exception e) {
Log.e(RetrieveInfoctivity.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
}
//StartSetupActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartSetupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
//FragmentsActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentsActivity extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
}
First of all whenever you want to disable back press just override onBackPressed() method and remove super. like this:
#Override
public void onBackPressed() {
//super.onBackPressed();
}
Second you'r using application context to show toast. use activity context.
Toast.makeText(this or YourActivity.this, "Setup Complete!", Toast.LENGTH_LONG).show();
Third just add this attribute into your manifest class. This will avoid recrating your activity when orientation change
android:configChanges="orientation"
I'll answer these in order:
Back Button
You can override onBackPressed in your Activity and determine if you want to consume it or let Android process it.
#Override
public void onBackPressed()
{
// Set this how you want based on your app logic
boolean disallowBackPressed = false;
if (!disallowBackPressed)
{
super.onBackPressed();
}
}
Toasts
Toasts are enqueued with the Notification Manager. If you show multiple Toasts in a row, they get queued up and shown one at a time until the queue is empty.
Locking Orientation For Activity
Use android:screenOrientation="landscape" or android:screenOrientation="portrait" on your activity element in your manifest to lock the orientation.
I think that these questions should be asked separately, because the answer in detail to every item of your question is too long, but I hope this helps:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The
problem is I don't want the user to click on Back at a certain point
in my application. I don't want to disable the back button completely
in my application, only when one intent is called. How can I do that?
You can override the onBackPressed on the activities you don't want the user to go back.
#Override
public void onBackPressed() {
//Leave it blank so it doesn't do anything
}
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my
application, some of the toast notifications are residual and are
popping outside of my application. Is there a reason for that? Did I
miss something in the activity lifecycle to handle the cancellation of
toasts at a certain point?
I think that the reason behind that is that toast go into a que, and are showed in order, even if the app is no longer visible.
Lastly, this one is rather tough to solve. How do I lock my screen so
that when the user rotates the device, that the activity doesn't not
get called again and the asynctask can still resume without starting
over again?
For this, you can use the following code in your manifest
android:configChanges="orientation|screenSize"/>
However this is NOT recommended by google, I suggest you read the following link to get a little more information on how to handle orientation changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html
I am writing a code for going to the next page after clicking a button so I have written the code that I have mentioned below i just want to confirn that it is correct as i cant check it now, I know this is silly but I need help
package com.example.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent nextScreen = new Intent(getApplicationContext(), JewelInfo.class);
// TODO Auto-generated method stub
startActivity(nextScreen);
}
});
}
}
Assuming that your JewelInfo extends from an Activty it looks fine.
I think you should use Intent nextScreen = new Intent(DetailsActivity.this, JewelInfo.class); instead of getApplicationContext()
The correctness of code is never checked just by looking at a bit of code. Syntactically, it seems to not contain an error. Semantically, how should we know? You need to define what you want to do, how you want it to look, etc. Basically, what are the requirements?
We can then validate the code against the requirements but not assess the correctness as that is only discerned by executing the code and evaluating the result of the execution on the device it is executed against the requirements.
use DetailsActivity.this instead of getApplicationContext(), and declare your JewelInfo activity on the manifest file : <activity android:name=".JewelInfo" />.Check this tutorial about how to switch between activities and pass data between them
Good day I have been doing some coding in the for my android program and i tried playing a music with this code right here android the lowest build is 2.2 and highest is 4.2.2 also using eclipse to do this and the device emulator is nexus one
this in the globe
MediaPlayer Sound;
and this is in the under the setContentView
Sound = MediaPlayer.create(Splash.this, R.raw.kalimba);
Sound.start();
and this is the entire code
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
MediaPlayer Sound;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Sound = MediaPlayer.create(Splash.this, R.raw.kalimba);
Sound.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openStartingPoints = new Intent("com.mysampleapp.simplybel.MainActivity");
startActivity(openStartingPoints);
}//this is the end for the finally
}//this is the end for the run
};//this is the end for the thread timer
timer.start();
}//this is the end for the oncreate
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Sound.release();
finish();
}
}
can anybody help me with this one?
It may be coming from your intent. What exactly are you trying to do with this intent?
The correct syntax for an explicit intent should be like in this intent tutorial. For example,
Intent openStartingPoints=new Intent(context,MainActivity.class); and context must be outside the thread like Context context; as a global variable declaration and instantiate it with context=this; inside of onCreate() to set it to the context of the current activity.
As another suggestion, you should always name variable names in camel case so the first letter should be lowercase.
Let me know if this changes anything. Other than that I can't see any problems with the code provided.