Transition to a black screen - java

I believe I have my code set up correctly but when I try to debug it, after it transitions from the splash screen it just goes right to a black screen. I know I imported the layout correctly but it still goes black.
This is the code for the splash screen
package com.example.equate.jones;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class EJ_Splash extends Activity {
protected boolean _active = true;
protected int _splashTime = 3000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ej__splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(4000);
}
}
catch(InterruptedException e) {
// do nothing
} {
finish();
Intent i = new Intent(getApplicationContext(),EJ_Board.class);
startActivity(i);
}
}
};
splashTread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ej__splash, menu);
return true;
}
}
This is the code for the screen it is supposed to transition to.
package com.example.equate.jones;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class EJ_Board extends Activity {
private ImageView button1;
final MediaPlayer mp = MediaPlayer.create(this, R.raw.warm);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ej_board);
button1=(ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
mp.start();
}
});
}
}
This is the xml for EJ_Board
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>

I think your problem is with the ImageView. You need to add an image to your drawable folder, then change your android:src="#drawable/ic_launcher" to the name of the image you saved. This will give you the image you need for your button. Hope that helps
Edit:
For your splash screen, try something like this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent homeIntent = new Intent().setClass(SplashActivity.this, HomeActivity.class);
startActivity(homeIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Then in your home activity you can set your menu:
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.locationButton:
Intent locationIntent = new Intent(this, LocationActivity.class);
startActivity(locationIntent);
return true;
case R.id.diningButton:
Intent diningIntent = new Intent(this, DiningActivity.class);
startActivity(diningIntent);
return true;
case R.id.topXXVButton:
Intent topIntent = new Intent(this, DiningActivity.class);
startActivity(topIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(EJ_Splash.this, EJ_Board.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}

Related

How do i modify data on my MainActivity from Settings Activity?

I've tried many other threads and articles but I just can't find the right stuff that I am looking for.
So I have a MainActivity and a SettingsActivity both are java classes. In my main activity there is a button when pressed, increases the count by +1, and shows it on a TextView, it also makes the device vibrate on every increment/Every button press. I want to make a switchpreference in SettingsActivity which if kept off/false, turns off the vibration on button press and if kept on/true, turns on the vibration on button press.
I don't know how to retrieve the state of SwitchPreferenceCompat(ON OR OFF) from SettingsActivity and use it in the MainActivity, so if the user turns the switch off in setting activity, the vibration should stop on button press which is in MainActivity.
I have already used Shared Preferences in MainActivity for saving the current count/number when App is closed and resumes from the same count when reopened.
MainAcitivity
package com.saad.tapcounter;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView ;
int Start;
TextView txt;
Button btnU,btnT,btnR;
Switch sw,sw2;
private ConstraintLayout Clayout;
Vibrator vibe;
Boolean switchPref;
SharedPreferences sharedPreferences;
private static long back_pressed;
private Vibrator Vibrator;
//Double Tap Exit
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
//Inflater for Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
//Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.menui1:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbarid);
setSupportActionBar(toolbar);
MobileAds.initialize(this, "-APPID-");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
vibe =(Vibrator)getSystemService(VIBRATOR_SERVICE);
Clayout = findViewById(R.id.MainLayout);
btnT = findViewById(R.id.tapbtn);
btnR = findViewById(R.id.resetbtn);
btnU = findViewById(R.id.undobtn);
sw = findViewById(R.id.swch);
sw2 = findViewById(R.id.darkswch);
txt = findViewById(R.id.txtv);
txt.setTextColor(Color.BLACK);
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
loadData();
setData();
incrementbtn();
undobtn();
resetbtn();
switchbtn();
themeswitch();
}
public void loadData(){
sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
}
private void setData(){
Start = sharedPreferences.getInt("0",0);
if(Start==0){
txt.setText("0");
}
else{
txt.setText(Integer.toString(Start));
}
}
public void incrementbtn(){
btnT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incvibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start += 1;
txt.setText(Integer.toString(Start));
txtresize();
} else {
Start += 1;
txt.setText(Integer.toString(Start));
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void undobtn(){
btnU.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
undovibe();
if (Start != 0) {
Start = sharedPreferences.getInt("0", 0);
Start -= 1;
txt.setText(Integer.toString(Start));
}
else{
return;
}
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void resetbtn(){
btnR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetvibe();
Start = 0;
txt.setText(Integer.toString(Start));
sharedPreferences.edit().putInt("0", Start).apply();
}
});
}
public void switchbtn(){
sw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw.isChecked()) {
btnR.setEnabled(false);
btnT.setEnabled(false);
btnU.setEnabled(false);
txt.setTextColor(Color.RED);
}
else{
btnR.setEnabled(true);
btnT.setEnabled(true);
btnU.setEnabled(true);
if(sw2.isChecked()){
txt.setTextColor(Color.WHITE);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void themeswitch(){
sw2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sw2.isChecked()){
Clayout.setBackgroundColor(Color.DKGRAY);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.WHITE);
}
}
else{
Clayout.setBackgroundColor(Color.WHITE);
if(sw.isChecked()){
txt.setTextColor(Color.RED);
}
else{
txt.setTextColor(Color.BLACK);
}
}
}
});
}
public void txtresize(){
if(Start > 1000 && Start < 10000){
txt.setTextSize(80);
}
else if (Start > 10000 && Start < 100000){
txt.setTextSize(60);
}
else if (Start > 100000){
txt.setTextSize(40);
}
else{
return;
}
}
StringBuilder info = new StringBuilder();
public void undovibe(){
vibe.vibrate(100);
}
public void resetvibe(){
vibe.vibrate(150);
}
public void incvibe(){
vibe.vibrate(40);
}
}//Real one
SettingActivity (created it from NEW > SettingActivity)
I did try some stuff by myself in here but it crashed my app.
package com.saad.tapcounter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
root_preference.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory app:title="Settings"
app:iconSpaceReserved="false">
<SwitchPreferenceCompat
app:key="Switchsett1"
app:title="Vibration"
app:summaryOff="Turn Vibration On"
app:summaryOn="Turn Vibration Off"
app:iconSpaceReserved="false"
app:defaultValue="true"
/>
<SwitchPreferenceCompat
app:key="Switchset2"
app:iconSpaceReserved="false"
app:summaryOff="#string/attachment_summary_off"
app:summaryOn="#string/attachment_summary_on"
app:title="#string/attachment_title" />
</PreferenceCategory>
</PreferenceScreen>
I don't know how to retrieve the state of switch(ON OR OFF) from SettingsActivity
To get the value of SwitchPreferenceCompat from shared preference, then you need to retrieve it as a Boolean
Now the key of your first SwitchPreferenceCompat is Switchsett1, so to retrieve the value of this:
public class MainActivity extends AppCompatActivity {
Boolean switchPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
switchPref = prefs.getBoolean("Switchsett1", false);
Toast.makeText(this, String.valueOf(switchPref), Toast.LENGTH_SHORT).show(); // shows true if the SwitchPreferenceCompat is ON, and false if OFF.
Now the Toast in the above script shows true if the SwitchPreferenceCompat is ON, and false if it's OFF.
You can do the same for Switchset2 SwitchPreferenceCompat

Losing state of the activity when navigating from notification to activity

I have an activity named Player Activity in which I am streaming music with the help of MediaPlayer API. Whenever my activity is created a notification is displayed which has some basic control of the music player.
So when I tap on my notification it jumps back to the Player Activity, but the state of the activity is lost.
Before tapping on notification :
After tapping on notification :
Here is the code of my notification's Pending Intent
Intent notifyIntent = new Intent(context, PlayerActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
notifyIntent.setAction("android.intent.action.MAIN");
notifyIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Here is the code for PlayerActivity.java :
package com.example.user.musicplayer;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.concurrent.TimeUnit;
import de.hdodenhof.circleimageview.CircleImageView;
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener{
private static Button btn_play_pause;
private Button btnToggleRepeat;
private Button btnStop;
private SeekBar seekBar;
private TextView textView;
public static MediaPlayer mediaPlayer;
private int mediaFileLength;
private int realtimeLength;
private String musicUrl;
private String imageUrl;
final Handler handler = new Handler();
private boolean isRepeat;
private CircleImageView musicImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Log.d("TAG", "onCreate");
NotificationGenerator.customBigNotification(getApplicationContext());
musicUrl = getIntent().getStringExtra("musicUrl");
imageUrl = getIntent().getStringExtra("imageUrl");
seekBar = (SeekBar)findViewById(R.id.seekbar);
seekBar.setMax(99); // 100% (0~99)
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaPlayer.isPlaying())
{
SeekBar seekBar = (SeekBar)v;
int playPosition = (mediaFileLength/100)*seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
}
return false;
}
});
textView = (TextView)findViewById(R.id.txtTime);
btnToggleRepeat = findViewById(R.id.btnRepeat);
btnStop = findViewById(R.id.btnStop);
musicImage = findViewById(R.id.musicImgView);
Picasso.get().load(imageUrl).placeholder(R.drawable.music).error(R.drawable.music).into(musicImage);
btn_play_pause = (Button) findViewById(R.id.btnTogglePlay);
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(PlayerActivity.this);
AsyncTask<String,String,String> mp3Play = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait");
mDialog.show();
}
#Override
protected String doInBackground(String... params) {
try{
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
}
catch (Exception ex)
{
}
return "";
}
#Override
protected void onPostExecute(String s) {
mediaFileLength = mediaPlayer.getDuration();
realtimeLength = mediaFileLength;
if(!mediaPlayer.isPlaying())
{
playMusic();
}
else
{
pauseMusic();
}
updateSeekBar();
mDialog.dismiss();
}
};
mp3Play.execute(musicUrl); // direct link mp3 file
}
});
btnToggleRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isRepeat){
isRepeat = false;
mediaPlayer.setLooping(false);
btnToggleRepeat.setText("Repeat");
}
else{
isRepeat = true;
mediaPlayer.setLooping(true);
btnToggleRepeat.setText("Single");
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.pause();
mediaPlayer.stop();
}
catch (Exception e){
Toast.makeText(PlayerActivity.this, "Opps! sorry something bad happened", Toast.LENGTH_SHORT).show();
}
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
public void pauseMusic() {
mediaPlayer.pause();
btn_play_pause.setText("Play");
}
public void playMusic() {
mediaPlayer.start();
btn_play_pause.setText("Pause");
}
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d",TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", "onResume");
}
#Override
protected void onStart() {
super.onStart();
Log.d("TAG", "onStart");
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
if(!mediaPlayer.isLooping())
btn_play_pause.setText("Play");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("notificationPlayer","Received Cancelled Event");
}
}
}
Thanks in advance. Pardon me if the explanation is not clear, because if i might have right words to explain it, I would have googled it.
Add this to your PlayerActivity activity in manifest :
android:launchMode="singleTask"
And use these flags in the intent for pendingintent :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

Display splashscreen & then AppIntro(First time launch) than mainactivity not working

I have made android app in which onLaunch I want to show SplashScreen for 3 second & then AppInro(If First time launch in slide) & then MainActivity launches. Actually I have done made splashscreen activity at the end but I set it up all properly but now After splashScreen MainActivity Starts directly. AppIntro not showing(Even in first time launch as well) Before adding SplashScreen activity AppIntro was working fine.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.introslider">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SpashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="Order Medicines"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="info.androidhive.welcomeslider.MainActivity"
//In above line code it shows Can not resolve symbol MainActivity
android:label="#string/title_activity_splash"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
SplashScreen
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SpashScreen extends Activity {
private PrefManager prefManager;
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SpashScreen.this, MainActivity.class);
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
AppIntro(WelcomeActivity)
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WelcomeActivity extends AppCompatActivity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_slide1,
R.layout.welcome_slide2,
R.layout.welcome_slide3,
R.layout.welcome_slide4};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
You are never opening WelcomeActivity - you open MainActivity directly from SplashActivity, so PrefManager is never queried.
What you should do in SplashActivity is:
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SplashScreen.this, MainActivity.class)
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
And remove all first time launch checking code from WelcomeActivity.
You didn't initialize prefManager, Try initializing it first.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SpashScreen extends Activity {
private PrefManager prefManager;
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// HERE prefManager INITIALIZED
prefManager = getPreferences(Context.MODE_PRIVATE);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SpashScreen.this, MainActivity.class);
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
You didn't initialize prefManager,this is the right way
this is worked for me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
try {
int netStatus = NetworkUtil.getConnectivityStatus(getBaseContext());
if (netStatus == 0) {
Intent intent = new Intent(SplashScreen.this,NoInternetActivity.class);
startActivity(intent);
finish();
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
PrefManager prefManager = new PrefManager(getApplicationContext());
// This method will be executed once the timer is over
// Start your app main activity
if(prefManager.isFirstTimeLaunch()){
intent = new Intent(SplashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(true);
}else {
intent = new Intent(SplashScreen.this,MainActivity.class);
}
startActivity(intent);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}catch (RuntimeException e){
e.printStackTrace();
}
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}

Method to stop Android MediaPlayer using the same button?

I want to stop the Android MediaPlayer in my App using the same button which I use for starting it. As you can see from the sources below, I declared the onClick function of my button in the activity_main.xml. When clicked, the buttons value changes from an triangle to a square, if I click it again, it changes back so there is no problem with this.
The tick(); function is configured to get either the string "start" or the string "stop" dependent on which version of the button has been pressed.
Also the player is very laggy. It should play the click sound every second (for testing if this even works) but it is very laggy.
Here is my MainActivity
package net.k40s.metronome;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Toast;
import android.os.Handler;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
NumberPicker inputBPM;
ImageView outputFlash;
Button buttonPlay;
protected PowerManager.WakeLock mWakeLock;
final Handler metronomeHandler = new Handler();
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
inputBPM = (NumberPicker) findViewById(R.id.inputBPM);
outputFlash = (ImageView) findViewById(R.id.imageClick);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
inputBPM.setMinValue(20);
inputBPM.setMaxValue(150);
inputBPM.setValue(120);
inputBPM.setWrapSelectorWheel(true);
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Metronome Active");
this.mWakeLock.acquire();
}
}
#Override
public void onDestroy() {
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
this.mWakeLock.release();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent startActivity = new Intent(this, SettingsActivity.class);
startActivity(startActivity);
return true;
}
if (id == R.id.action_mail){
sendMailToMe();
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
public static class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
private void tick(String what) {
if (what.equals("start")) {
metronomeHandler.post(metronomeRunnable);
}
if (what.equals("stop")){
if(mp.isPlaying())
{
// TODO stop media playback
}
}
}
final Runnable metronomeRunnable = new Runnable() {
public void run(String what) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.click);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
};
public void playBeat(final View v) {
String activeText = (String) buttonPlay.getText();
if (activeText.equals(getResources().getString(R.string.value_button_play))) {
buttonPlay.setText(R.string.value_button_stop);
inputBPM.setValue(121);
int bpm = inputBPM.getValue();
SharedPreferences sp1 = PreferenceManager.getDefaultSharedPreferences(this);
String pref_measure = sp1.getString("pref_measure", "");
if (pref_measure.equals("4")) {
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {tick("start");}
}, 0, 1000);
}
if (pref_measure.equals("3")) {
/*
Dreivierteltakt start
*/
}
if (pref_measure.equals("2")) {
/*
Zweivierteltakt start
*/
}
if (pref_measure.equals("6")) {
/*
Sechsachteltakt start
*/
}
}
else if (activeText.equals(getResources().getString(R.string.value_button_stop))) {
buttonPlay.setText(R.string.value_button_play);
tick("stop");
}
}
public void sendMailToMe(){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"lukas#k40s.net"});
i.putExtra(Intent.EXTRA_SUBJECT, "I want to say hello.");
i.putExtra(Intent.EXTRA_TEXT , "Hey,");
try {
startActivity(Intent.createChooser(i, getResources().getString(R.string.choose_mail)));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, getResources().getString(R.string.no_clients), Toast.LENGTH_SHORT).show();
}
}
}
And here is my activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:soundEffectsEnabled="true"
tools:context=".MainActivity">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputBPM"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/value_button_play"
android:id="#+id/buttonPlay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="playBeat" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/bpm"
android:id="#+id/textView"
android:layout_above="#+id/inputBPM"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageClick"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/flash0" />
</RelativeLayout>
You can find the whole code at GitHub
Thanks for your help. Sorry if I'm really that stupid and overlooked something really obvious.
So try this code below, basically you need to make your timer a field member and then cancel it when they want to stop and then reinitialize it when they click play. I tested it and it works for me. (unrelated code was omitted)
MediaPlayer mp;
Timer myTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
inputBPM = (NumberPicker) findViewById(R.id.inputBPM);
outputFlash = (ImageView) findViewById(R.id.imageClick);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
inputBPM.setMinValue(20);
inputBPM.setMaxValue(150);
inputBPM.setValue(120);
inputBPM.setWrapSelectorWheel(true);
mp = MediaPlayer.create(getApplicationContext(), R.raw.click);
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Metronome Active");
this.mWakeLock.acquire();
}
}
#Override
public void onDestroy() {
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
this.mWakeLock.release();
}
if (mp != null) {
mp.release();
}
super.onDestroy();
}
private void tick(String what) {
if (what.equals("start")) {
mp.start();
}
else if (what.equals("stop")) {
mp.pause();
}
}
public void playBeat(final View v) {
String activeText = (String) buttonPlay.getText();
if (activeText.equals(getResources().getString(R.string.value_button_play))) {
buttonPlay.setText(R.string.value_button_stop);
inputBPM.setValue(121);
int bpm = inputBPM.getValue();
myTimer = new Timer();
SharedPreferences sp1 = PreferenceManager.getDefaultSharedPreferences(this);
String pref_measure = sp1.getString("pref_measure", "");
if (pref_measure.equals("4")) {
myTimer.schedule(new TimerTask() {
#Override
public void run() {tick("start");}
}, 0, 1000);
}
}
else if (activeText.equals(getResources().getString(R.string.value_button_stop))) {
buttonPlay.setText(R.string.value_button_play);
myTimer.cancel();
myTimer.purge();
myTimer = null;
tick("stop");
}
}

first activity view does not appear

I am new to android. I have two activities Splash and MainActivity. When I launch my application the Splash activity starts(as its supposed to be), it plays the sound but the background image does not appear and some seconds later my MainActivity starts. Thanks in advance!
code for MainActivity class
Package com.example.button;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int counter;
Button add;
Button sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter=0;
add=(Button)findViewById(R.id.button1);
sub=(Button)findViewById(R.id.button2);
display=(TextView)findViewById(R.id.textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void add(View view)
{
counter=counter+1;
display.setText("your total is"+counter);
}
public void sub(View view)
{
counter--;
display.setText("your total is"+counter);
}
}
code for Splash class
package com.example.button;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity{
MediaPlayer ourSong;
Thread timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this,R.raw.addicted);
ourSong.start();
timer=new Thread();
timer.start();
run();
//{
//};
}
public void run()
{
try {
timer.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally {
Intent openStartingPoint=new Intent("com.example.button.MAINACTIVITY");
startActivity(openStartingPoint);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSong.release();
}
}
code for splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/feather">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
I think you have not correctly used Thread. change these three lines of your code
timer=new Thread();
timer.start();
run();
to
timer=new Thread(new Runnable(){
public void run() {
try {
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally {
Intent openStartingPoint=new Intent("com.example.button.MAINACTIVITY");
startActivity(openStartingPoint);
}
}
});
timer.start();
and remove run method from your activity.
by this way you let the splash activity to appear for 5 seconds on screen.
in your splash.xml take a imageview and put your image file there.
e.g android:src="file.gif"
hope this helps you`
use this code as your splash activity:
public class SplashActivity extends Activity {
int SPLASH_DISPLAY_LENGHT = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_form);
InitilizeUi();
}
private void InitilizeUi() {
// play your sound
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent mainIntent = new Intent(SplashActivity.this, AboutActivity.class);
SplashActivity.this.startActivity(mainIntent);
SplashActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
}

Categories