在我的应用程序中,我正在播放本地存储中的音频文件,而在播放音频时,如果我点击后退按钮,我的应用程序就会崩溃。我尝试应用stop(),release(),reset()和其他媒体播放器功能。
logcat的:
11-30 16:09:09.473 2270-2468/? E/SEC_DRM_PLUGIN_Omafl: OmaPlugin::onOpenDecryptSession(fd)::Drm2IsDrmFileByExtFd::file is NOT DRM by extension
11-30 16:09:09.473 2270-2468/? E/PrGenericPlugin: PrGenericPlugin::onOpenDecryptSession() onCanHandle error
11-30 16:09:09.478 8675-8761/? E/MediaPlayer: Should have subtitle controller already set
11-30 16:09:09.478 2271-2271/? E/MediaPlayerService: WFD client is not created
11-30 16:09:09.478 2271-2271/? E/MediaPlayerService: offset error
11-30 16:09:09.478 8675-8761/? E/MediaPlayer: Unable to create media player
11-30 16:09:09.483 8675-8761/? E/MediaPlayer: stop called in state 1
11-30 16:09:09.483 8675-8761/? E/MediaPlayer: error (-38, 0)
11-30 16:09:09.483 8675-8761/? E/MediaPlayer: Should have subtitle controller already set
11-30 16:09:09.488 2271-8776/? E/OMXNodeInstance: getParameter(133:SEC.mp3.dec, ??(0x7f010008)) ERROR: UnsupportedIndex(0x8000101a)
11-30 16:09:21.548 2912-3282/? E/Watchdog: !@Sync 9745 [11-30 16:09:21.553]
码
public class DetailPageFragment extends Fragment implements OnCompletionListener,MediaPlayer.OnErrorListener {
MediaPlayer mediaPlayer;
public OnDetailPageLoadListener mListener;
public Boolean isLoaded = false;
String idToPass;
String buttonToPass;
public int headCellHeight;
public String headword;
public String hwdID;
public String homNum;
public String senseNum;
Thread displayThread;
Handler handler;
public boolean thesRedirect;
public boolean sendBack;
public String imageName;
ProgressBar pb_detail;
Tracker t;
public int scrollYpostion;
public static final String PREFS_NAME = "LDOCE6PrefsFile";
boolean isRedirected;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_detail_page_fragment, null);
return v;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnDetailPageLoadListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
// Get the Tracker and Initialise it
t = ((LDOCEApp) getActivity().getApplication()).getTracker(
LDOCEApp.TrackerName.APP_TRACKER);
t.setScreenName("Word Description Page");
t.send(new HitBuilders.AppViewBuilder().build());
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
try {
imageName = getImageDetailFromDB(headword);
} catch (JSONException e) {
e.printStackTrace();
}
pb_detail = (ProgressBar) getActivity().findViewById(R.id.pb_detail);
pb_detail.getIndeterminateDrawable().setColorFilter(Color.rgb(103, 144, 177), Mode.MULTIPLY);
final WebView webView = (WebView) getActivity().findViewById(R.id.wv_headCell);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
if (webView != null) {
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(getResources(), getActivity(), this), "JavaScriptInterface");
webView.setWebViewClient(new myWebClient());
WebSettings webViewSettings = webView.getSettings();
SharedPreferences fontSizePreferences = getActivity().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
int fontSizeValue = fontSizePreferences.getInt("FONT_VALUE", 0);
if (fontSizeValue==0)
webViewSettings.setTextZoom(webViewSettings.getTextZoom()+1);
if (fontSizeValue==2)
webViewSettings.setTextZoom(webViewSettings.getTextZoom()+3);
if (fontSizeValue==4)
webViewSettings.setTextZoom(webViewSettings.getTextZoom()+7);
if (fontSizeValue==8)
webViewSettings.setTextZoom(webViewSettings.getTextZoom()+15);
}
// Handler to Update the UI
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
//Update the History Table for current tapped word - ordering the History Table
updateHistoryTable(headword,hwdID);
//checks whether Detail Page is still in Loading state or not
isLoaded = true;
if (webView!=null) {
String msgToLoad=String.valueOf(msg.obj);
if(String.valueOf(msg.obj).contains("<expandHWD/>")){
System.out.println("Replace the String");
String hwd=headword;
if(hwd!=null){
msgToLoad=msgToLoad.replaceAll("<expandHWD/>",hwd+" ");
}
}
//putting the homnum and sense value value
if(String.valueOf(msg.obj).contains("replaceHomnum") && !isRedirected){
msgToLoad=msgToLoad.replace("replaceHomnum",homNum);
isRedirected=true;
}
if(String.valueOf(msg.obj).contains("replaceSensenum")){
msgToLoad=msgToLoad.replace("replaceSensenum",senseNum);
}
if(String.valueOf(msg.obj).contains("replaceId")){
msgToLoad=msgToLoad.replace("replaceId","");
}
//replaceImageDetails
if(String.valueOf(msg.obj).contains("replaceImageDetails")){
msgToLoad=msgToLoad.replace("replaceImageDetails",imageName);
}
if(thesRedirect) {
//while Loading - check this ia tablet
// If this is tablet - we have to calculate the Headcell height to show thesaurus content
if(Utils.isTablet(getActivity())) {
//check in mastexsltablet - for a variable ThesNotTapped
if (String.valueOf(msg.obj).contains("ThesNotTapped")) {
msgToLoad = msgToLoad.replace("ThesNotTapped", "ThesTapped");
msgToLoad = msgToLoad.replace("thesHeadwrdId", hwdID);
}
}
}
webView.loadDataWithBaseURL("file:///android_asset/www/", msgToLoad, "text/html", "UTF-8", null);
webView.setScrollY(scrollYpostion);
}
} catch (NullPointerException e) {
e.printStackTrace();
Log.e("DetailPage", "Page didn't load fully and error is " + e.getMessage());
}
}
};
//Create a separate Thread for content to display in detail page - This will run in Background Process,without blocking UI
displayThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String contentsToDisplay = null;
contentsToDisplay = displayInfo();
Message msg = new Message();
msg.obj = contentsToDisplay;
if (contentsToDisplay != null) {
handler.sendMessage(msg);
}
} catch (Throwable t) {
Log.v("Content Display Thread", "Thread Exception" + t);
mListener.detailPageInterrupted(true);
}
}
});
displayThread.start();
mListener.detailPageLoaded(true);
//Check if it is phone - navigate to AdditionalInfo - default for phone headcellheight is 0and thesaurus ItemId is 1004
if(!Utils.isTablet(getActivity()) && (thesRedirect)){
navigateToAdditionalInfo(hwdID,0,1004);
thesRedirect=false;
}
}
public class myWebClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
try {
if (pb_detail != null)
pb_detail.setVisibility(View.GONE);
} catch (NullPointerException e) {
Log.e("DetailPage", "Page didn't load fully and error is" + e.getMessage());
}
}
}
public void playSound(String id, String buttonClicked, Context context) {
DbConnection dbPath = new DbConnection();
SQLiteDatabase db = dbPath.getDbConnection();
boolean isInternetOn = false;
boolean isPlayed = false;
if(Utils.isTablet(getContext().getApplicationContext())){
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Check if the current existence of DB is not null
if (db != null && !id.equalsIgnoreCase("")) {
String fileName = null;
Uri url = null;
//Check for UK English
if (buttonClicked.equals("uk")) {
// Tracking for SlideMenu Button Click
t = ((LDOCEApp) getActivity().getApplication()).getTracker(LDOCEApp.TrackerName.APP_TRACKER);
// Set the screen as Detail Page
t.setScreenName("Word Description Page");
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory("audio_button_action")
.setAction("uk_button_click")
.setLabel("UKbuttonTapped")
.build());
// Query to get the records from uksound table
String query = String.format("select * from uksound where id=?");
Cursor cur = db.rawQuery(query, new String[]{id});
//Check id presents in the table
while (cur.moveToNext()) {
fileName = cur.getString(cur.getColumnIndex("filename"));
}
if (Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + ".media_files_228" + File.separator + "ldoce6_hwd_gb" + File.separator + fileName;
try {
FileInputStream fis = new FileInputStream(filePath);
String entry = null;
while ((entry = fis.toString()) != null) {
if (!entry.toString().isEmpty()) {
File Mytemp = File.createTempFile("TCL", "mp3", getActivity().getCacheDir());
Mytemp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(Mytemp);
for (int c = fis.read(); c != -1; c = fis.read()) {
try {
fos.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
mediaPlayer = new MediaPlayer();
fos.close();
FileInputStream MyFile = new FileInputStream(Mytemp);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(MyFile.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
} else {
Toast.makeText(getContext(), R.string.unable_to_locate_media_files, Toast.LENGTH_LONG).show();
}
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.stop();
// mediaPlayer = null;
mediaPlayer.release();
}
}
}
if (fileName != null)
url = Uri.parse("http://eltapps.pearson.com/ldoce6app/ldoce6_hwd_gb/");
}
//Check for US English
else if (buttonClicked.equals("us")) {
t = ((LDOCEApp) getActivity().getApplication()).getTracker(LDOCEApp.TrackerName.APP_TRACKER);
// Set the screen as Detail Page
t.setScreenName("Word Description Page");
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory("audio_button_action")
.setAction("us_button_click")
.setLabel("USbuttonTapped")
.build());
// Query to get the records from ussound table
String query = String.format("select * from ussound where id=?");
Cursor cur = db.rawQuery(query, new String[]{id});
//Check id presents in the table
while (cur.moveToNext()) {
//Assign the filename
fileName = cur.getString(cur.getColumnIndex("filename"));
}
if (Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + ".media_files_228" + File.separator + "ldoce6_hwd_us" + File.separator + fileName;
try {
FileInputStream fis = new FileInputStream(filePath);
String zipFileName = "convertMp3ToDb" + File.separator + "ldoce6_hwd_us" + File.separator + fileName;
String entry = null;
while ((entry = fis.toString()) != null) {
if (!entry.toString().isEmpty()) {
File Mytemp = File.createTempFile("TCL", "mp3", getActivity().getCacheDir());
Mytemp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(Mytemp);
for (int c = fis.read(); c != -1; c = fis.read()) {
try {
fos.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
mediaPlayer = new MediaPlayer();
fos.close();
FileInputStream MyFile = new FileInputStream(Mytemp);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(MyFile.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
} else {
Toast.makeText(getContext(), R.string.unable_to_locate_media_files, Toast.LENGTH_LONG).show();
}
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.stop();
// mediaPlayer = null;
mediaPlayer.release();
}
}
}
if (fileName != null)
url = Uri.parse("http://eltapps.pearson.com/ldoce6app/ldoce6_hwd_us/");
} else if (buttonClicked.equals("example")) {
//fetch the filename from exampleSound table from database
String query = String.format("select * from exasound where id=?");
Cursor cur = db.rawQuery(query, new String[]{id});
while (cur.moveToNext()) {
fileName = cur.getString(cur.getColumnIndex("filename"));
}
if (fileName != null)
url = Uri.parse("http://eltapps.pearson.com/ldoce6app/ldoce6_exa_pron/");
// Toast.makeText(context,R.string.sorry_audio_is_not_available,Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), R.string.unable_to_locate_media_files, Toast.LENGTH_LONG).show();
}
/*Get the file path url and convert to string
* Concatenate the filename with the file path url
* Initialise the mediaPlayer and assign the data source with the file path url*/
if (url != null) {
String filePath = url.toString();
filePath = filePath.concat(fileName);
idToPass = id;
buttonToPass = buttonClicked;
//Call for media player
playerStart(filePath);
} else {
callToWebView(id, buttonClicked);
}
// Close the DB Connection
db.close();
} else {
callToWebView(id, buttonClicked);
}
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
callToWebView();
return false;
}
@Override
public void onCompletion(MediaPlayer mp) {
/*Stop the loader and make the US or UK button back to normal state
call the restoreSoundButtonState in main.js */
Log.v("Completed", "Audio played successfully");
//Call for webView without params
callToWebView();
mediaPlayer = null;
}
//Method to call webView to update the button state
public void callToWebView(String idToPass, String buttonToPass) {
//Call to webView
final WebView webview = (WebView) getActivity().findViewById(R.id.wv_headCell);
final JSONObject jsonObject = new JSONObject();
try {
//Add idToPass and buttonToPass to json object
jsonObject.put("id", idToPass);
jsonObject.put("btn", buttonToPass);
} catch (JSONException e) {
e.printStackTrace();
}
//Run in a separate thread
if (webview != null)
webview.post(new Runnable() {
@Override
public void run() {
// Call the jQuery function from java code with the jsonObject
webview.loadUrl("javascript:restoreSoundButtonState(" + jsonObject.toString() + ")");
}
});
}
//function is used to scroll to a particular homnum entry in detail page
public void navigateToEntryWithHomnum() {
WebView webview = (WebView) getActivity().findViewById(R.id.wv_headCell);
if (webview != null) {
String function = "javascript:navigateToHomnumOrSense('" + homNum + "')";
webview.loadUrl(function);
}
}
//Media player call
private void playerStart(String filePath) {
//Make audio manager in stream music
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
try {
//Set url to data source
mediaPlayer.setDataSource(filePath);
//Prepare the player
mediaPlayer.prepare();
//Play the audio
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
//Handle scenarios for back, home button pressed and fragment cancelled
@Override
public void onPause() {
super.onPause();
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
callToWebView();
mediaPlayer.stop();
}
mediaPlayer = null;
if (displayThread.isAlive()) {
handler.removeCallbacksAndMessages(displayThread);
}
}
@Override
public void onStart() {
super.onStart();
//Remove any additional info if open for tab
if(Utils.isTablet(getActivity())) {
removeDummyCellAndCloseAdditionalInfo();
}
// Sending Hit to GA as Start of new Activity
GoogleAnalytics.getInstance(getActivity()).reportActivityStart(getActivity());
}
@Override
public void onStop() {
super.onStop();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
// Sending Hit to GA as End of Activity
GoogleAnalytics.getInstance(getActivity()).reportActivityStop(getActivity());
WebView webview = (WebView)getActivity() .findViewById(R.id.wv_headCell);
if (webview!=null)
scrollYpostion = webview.getScrollY();
}
/**
* performs search or copy
* It will execute the funtion in JavaScript and JSInterface will handle the action
* @param action action to be performed
*/
public void performSearchOrCopy(String action)
{
WebView webview = (WebView)getActivity() .findViewById(R.id.wv_headCell);
// to call the jQuery function from java code
JSONArray jsonArray = new JSONArray();
jsonArray.put(action);
if(webview!=null)
webview.loadUrl("javascript:getSelectedString(" + jsonArray.toString() + ")");
}
}
答案 0 :(得分:0)
尝试以下代码
@Override
public void onBackPressed() {
mediaPlayer.stop();
}
答案 1 :(得分:0)
覆盖活动中的onBackPressed()方法。
public void onBackPressed() {
if(media player is playing) {
// then stop it
}
super.onBackPressed();
}
答案 2 :(得分:0)
更改onPause()以释放所有MediaPlayer对象,而不是尝试重新启动当前播放的歌曲。
public void onPause()
{
super.onPause();
song.release();
song1.release();
//and so on
}`