2015-04-18 5 views
0

По какой-то причине на каждом другом телефоне, который я тестировал, приложение на музыку не перезапускается после того, как вы изменили представления и вернулись. Он отлично работает на моем телефоне, но два моих тестировщика и мой дочерний планшет делают то же самое. Когда вы открываете клавиатуру телефона или что-то, что заставляет музыку останавливать музыку, она выключается (плановая), но когда вы закрываете экран электронной почты/телефона, музыка не перезапускается (для них) это отлично работает для меня.Android Media Player Auto Restart

Как я могу обеспечить перезагрузку музыки после совершения вызова или отправить электронное письмо и вернуться к основному виду?

Вот моя основная Java Спасибо заблаговременно.

   package w1r.wilder1radio; 

       import android.annotation.TargetApi; 
       import android.app.Activity; 
       import android.app.AlertDialog; 

       import android.content.DialogInterface; 
       import android.content.Intent; 

       import android.media.AudioManager; 
       import android.media.MediaPlayer; 
       import android.net.Uri; 

       import android.os.Build; 
       import android.os.Bundle; 


       import android.util.Log; 

       import android.view.View; 

       import android.webkit.WebView; 
       import android.webkit.WebViewClient; 
       import android.widget.Button; 

       import android.widget.Toast; 

       import com.pushbots.push.Pushbots; 



       public class MainActivity extends Activity implements MediaPlayer.OnPreparedListener { 


       MediaPlayer mp; 

       //Button Names 
       Button btncall; 
       Button btnqrcode; 
       Button btnemail; 
       Button btnshare; 


       Button navfacebook; 
       Button navtwitter; 
       Button navgoogleplus; 


       @Override 
       public void onPrepared(MediaPlayer mp) { 


       if (!mp.isPlaying()) 
       if ((mp != null)) { 

        mp.start(); 
       } 

       } 

       @Override 
       protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_main); 
       Pushbots.sharedInstance().init(this); 
       AppRater.app_launched(this); 


       //Now Playing WebView 
       WebView view = (WebView) this.findViewById(R.id.webView); 
       view.setWebViewClient(new WebViewClient()); 
       view.getSettings().setJavaScriptEnabled(true); 
       String url2 = "http://markesswilder.com/w1rnowplaying.html"; 
       view.loadUrl(url2); 


       //Media Player 

       try { 

       mp = new MediaPlayer(); 
       String url = "http://75.126.73.136:8042/;"; 
       mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
       mp.setDataSource(url); 
       mp.prepareAsync(); 
       mp.setOnPreparedListener(this); 

       if (mp!=null) { 
        initMediaPlayer(); 
       } else if (!mp.isPlaying()) mp.start(); 
       } catch (Exception e) { 
       Log.i("ExceptionOnCreate:", e.getMessage()); 

       e.getMessage(); 
       Toast.makeText(this, 
         "Please check your WiFi/or Carrier Service and try again", Toast.LENGTH_LONG).show(); 
       } 


       //Button id 

       btncall = (Button) findViewById(R.id.btncall); 
       btnqrcode = (Button) findViewById(R.id.btnqrcode); 
       btnemail = (Button) findViewById(R.id.btnemail); 
       btnshare = (Button) findViewById(R.id.btnshare); 

       //Menu Buttons 

       navfacebook = (Button) findViewById(R.id.navfacebook); 
       navtwitter = (Button) findViewById(R.id.navtwitter); 
       navgoogleplus = (Button) findViewById(R.id.navgoogleplus); 


       //Button Clicks 

       btncall.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        sendToCall(); 

       } 
       }); 


       btnqrcode.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        sendToQrCode(); 

       } 
       }); 


       btnemail.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        goToEmail(); 


       } 

       }); 


       btnshare.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        goToShare(); 


       } 

       }); 


       navfacebook.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        sendToNavFaceBook(); 


       } 


       }); 


       navtwitter.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        sendToNavTwitter(); 


       } 


       } 

       ); 


       navgoogleplus.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
       sendToNavGooglePlus(); 


       } 


       } 

       ); 

       } 

       //??? 
       private void initMediaPlayer() { 

       } 

       //Button Clicks Handlers 

       @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
       protected void sendToCall() { 

       AlertDialog.Builder builder1 = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT); 
       builder1.setIcon(R.drawable.shoutoutslogo); 
       builder1.setTitle("Call Us"); 
       builder1.setInverseBackgroundForced(true); 
       builder1.setCancelable(false); 
       builder1.setMessage("Want to hear your voice on our station? " + 
        "Send us your name and where you're calling from. If we like it we'll put it on the air. " + 
        "Just remember to finish with - Wilder1Radio Go Ahead GET WILD!"); 
       builder1.setPositiveButton("I'M READY TO SHOUT", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        //if user pressed "yes", then open phone pad 
        Intent callIntent = new Intent(Intent.ACTION_VIEW); 
        callIntent.setData(Uri.parse("tel:+1 614-383-9939")); 
        startActivity(callIntent); 


       } 
       }); 
       builder1.setNegativeButton("NOT READY", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        //if user selects "No", cancel this dialog and continue with the app 
        dialog.cancel(); 
        Toast.makeText(MainActivity.this, "Continue to enjoy the music.", Toast.LENGTH_SHORT).show(); 
       } 
       }); 
       AlertDialog alert = builder1.create(); 
       alert.show(); 
       } 


       @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
       protected void sendToQrCode() { 

       AlertDialog.Builder builder2 = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK); 
       builder2.setIcon(R.drawable.qrwilder1radio); 
       builder2.setTitle("Scan Me"); 
       builder2.setInverseBackgroundForced(true); 
       builder2.setCancelable(false); 
       builder2.setMessage("Easily share this App with all your Android friends. " + 
        "Help us support Independent, Soul Music and Artists by simply having others scan this bar-code with any Android scan program and download this app. " + 
        "Share the music and share your love for independent artists around the world."); 

       builder2.setNegativeButton("Close", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        //if user selects "No", cancel this dialog and continue with the app 
        dialog.cancel(); 
        Toast.makeText(MainActivity.this, "Thank you for sharing the Music.", Toast.LENGTH_SHORT).show(); 
       } 
       }); 
       AlertDialog alert = builder2.create(); 
       alert.show(); 
       } 


       protected void goToEmail() { 
       Intent i = new Intent(Intent.ACTION_SEND); 
       i.setType("message/rfc822"); 
       i.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); 
       i.putExtra(Intent.EXTRA_SUBJECT, "I LOVE THIS STATION!!!"); 
       i.putExtra(Intent.EXTRA_TEXT, ""); 
       try { 
       startActivity(Intent.createChooser(i, "Send mail...")); 
       } catch (android.content.ActivityNotFoundException ex) { 
       Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); 

       } 
       } 


       protected void goToShare() { 
       Intent sharingIntent = new Intent(Intent.ACTION_SEND); 
       sharingIntent.setType("text/plain"); 
       String shareBody = "http://goo.gl/Y7sMvB"; 
       sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "You'll Love This App!!!"); 
       sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody); 
       startActivity(Intent.createChooser(sharingIntent, "Share via")); 



       } 


       //top nav buttons 

       protected void sendToNavFaceBook() { 
       String url = "https://www.facebook.com/pages/Wilder1Radio/125698310843952"; 
       Intent in = new Intent(Intent.ACTION_VIEW); 
       in.setData(Uri.parse(url)); 
       startActivity(in); 


       } 

       protected void sendToNavTwitter() { 
       String url = "https://twitter.com/Wilder1Radio"; 
       Intent in = new Intent(Intent.ACTION_VIEW); 
       in.setData(Uri.parse(url)); 
       startActivity(in); 
       mp.pause(); 

       } 

       protected void sendToNavGooglePlus() { 
       String url = "https://plus.google.com/u/0/107138907547512605174"; 
       Intent in = new Intent(Intent.ACTION_VIEW); 
       in.setData(Uri.parse(url)); 
       startActivity(in); 



       } 

       //Close App Alert 

       @Override 
       public void onBackPressed() { 
       //Opens alert message when back button is pressed when in main view 
       backButtonControl(); 
       } 

       public void backButtonControl() { 
       AlertDialog.Builder alertDialog = new AlertDialog.Builder(
        MainActivity.this); 
       //Dialog Title 
       alertDialog.setTitle("Closing W1R App"); 
       //Dialog Message 
       alertDialog.setMessage("Ready to go off the air?"); 
       //Add Icon to Dialog 
       alertDialog.setIcon(R.drawable.w1ricon); 
       //"Yes" Button 
       alertDialog.setPositiveButton("YES", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
          //If YES, close app completely 
          finish(); 
         } 
        }); 
       //"NO" Button 
       alertDialog.setNegativeButton("NO", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
          //If NO, show toast and close alert only 
          dialog.cancel(); 
          Toast.makeText(MainActivity.this, "Thank you for your support", Toast.LENGTH_SHORT).show(); 
         } 
        }); 
       //Showing Alert Message 
       alertDialog.show(); 
       } 


       @Override 
       public void onResume() { 
       super.onResume(); // Always call the superclass method first 
       // Play again, tough be carefull in the beggining for null pointers 
       } 

       @Override 
       public void onPause() { 
       super.onPause(); // Always call the superclass method first 
       // Stop playing, we are paused. Phone call, ... 
       } 

       @Override 
       protected void onStop() { 
       super.onDestroy(); 
       if(mp!=null){ 
       if(mp.isPlaying()){ 
        mp.stop(); 
       } 
       mp.release(); 
       mp = null; 
       } 

       } 
       } 

ответ

0

Есть два метода, которые следует переопределить

@Override 
public void onResume() { 
    super.onResume(); // Always call the superclass method first 
    // Play again, tough be carefull in the beggining for null pointers 
} 
@Override 
public void onPause() { 
    super.onPause(); // Always call the superclass method first 
    // Stop playing, we are paused. Phone call, ... 
} 
+0

Я постараюсь, что теперь спасибо. Добавляю ли я их в дополнение ко всему остальному или удаляя что-то? Я знаю, что мой код сумасшедший. Я просто учился, поэтому я ценю помощь. Спасибо. – Markess

+0

. Хорошо, я добавил код перед публичным void onStop Override, и он делает то же самое с ними. Мне сложно тестировать, потому что он отлично работает для меня, поэтому я действительно не уверен, что это такое. Два Android-телефона и Android-планшет мгновенно замораживаются, а затем нет музыки после нажатия одной из кнопок, которая меняет вид. – Markess

+0

Также после этого, когда вы нажимаете кнопку нажатия, чтобы закрыть, они получают сообщение об ошибке: «ОК, (извините, я не помню). Я не уверен, почему он работает для меня, но не для других. Еще раз спасибо. – Markess