簡體   English   中英

無法播放流媒體 onstart 方法 android

[英]unable to play streaming onstart method android

我是 Android 平台的應用程序開發人員。 現在我想當應用程序開始自動播放流媒體中的音樂時,不幸的是我不能這樣做,我有一個條件是檢查背景中的音樂,但這不起作用,因為應用程序開始流式傳輸音樂但是當我想要要停止它,它會啟動音樂和流媒體 stream 雙。

    playStop = findViewById(R.id.playStopBtn);
    nowPlaying = findViewById(R.id.radioStationNowPlaying);
    nowPlaying.setTypeface(dorcic);
    setIsPlaying(false);
    processPhoneListenerPermission();
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            if (tm != null) {
                if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
                    if (getIsPlaying()) {
                        stop();
                    }
                }
            }
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.intent.action.PHONE_STATE");
    registerReceiver(broadcastReceiver, filter);
    loadNowPlaying();
    playStop.setOnClickListener(view -> {
        if (isNetworkAvailable()) {
            if (getIsPlaying()) {
                stop();
            } else {
                play();
            }
        } else {
            Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_LONG).show();
        }
    });
}




private void loadNowPlaying() {
    Thread t = new Thread() {
        public void run() {
            try {
                while (!isInterrupted()) {
                    runOnUiThread(() -> reloadShoutCastInfo());
                    Thread.sleep(20000);
                }
            } catch (InterruptedException ignored) {
            }
        }
    };
    t.start();
}

private void reloadShoutCastInfo() {
    if (isNetworkAvailable()) {
        AsyncTaskRunner runner = new AsyncTaskRunner();
        runner.execute();
    }
}

@SuppressLint("StaticFieldLeak")
private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
        mmr.setDataSource(STREAMING_URL);
        nowPlayingData = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ICY_METADATA).replaceAll("StreamTitle", "").replaceAll("[=,';]+", "");
        mmr.release();
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        nowPlaying.setText(nowPlayingData);
    }
}

private void processPhoneListenerPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 121);
    }
}

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = null;
    if (cm != null) {
        networkInfo = cm.getActiveNetworkInfo();
    }
    return networkInfo != null && networkInfo.isConnectedOrConnecting();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == 121) {
        if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
            Toast.makeText(getApplicationContext(), "Permission not granted.\nWe can't pause music when phone ringing.", Toast.LENGTH_LONG).show();
        }
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

    @Override
    public void onBackPressed()
    {
        Toast.makeText(MainActivity.this,"לחצו על כפתור הבית לשמיעת הרדיו ברקע", Toast.LENGTH_LONG).show();

    }

private void setIsPlaying(boolean status) {
    SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE).edit();
    editor.putBoolean("isPlaying", status);
    editor.apply();
}

private boolean getIsPlaying() {
    SharedPreferences prefs = getApplicationContext().getSharedPreferences("isPlaying", MODE_PRIVATE);
    return prefs.getBoolean("isPlaying", false);
}

private void play() {
    setIsPlaying(true);
    Intent servicePlayIntent = new Intent(this, MyService.class);
    servicePlayIntent.putExtra("playStop", "play");
    startService(servicePlayIntent);
    playStop.setImageResource(R.drawable.ic_pause);
    Toast.makeText(getApplicationContext(), "מתנגן...", Toast.LENGTH_LONG).show();
}

private void stop() {
    setIsPlaying(false);
    Intent serviceStopIntent = new Intent(this, MyService.class);
    serviceStopIntent.putExtra("playStop", "stop");
    startService(serviceStopIntent);
    playStop.setImageResource(R.drawable.ic_play);
    Toast.makeText(getApplicationContext(), "עוצר...", Toast.LENGTH_LONG).show();
}

@Override
protected void onStop() {
    super.onStop();

}

@Override
protected void onStart() {
    play();
    super.onStart();
}

@Override
protected void onDestroy() {
    stopService(new Intent(getApplicationContext(), MyService.class));
    unregisterReceiver(broadcastReceiver);
    finish();
    super.onDestroy();
}

}

嘗試定義這個:

線程 t = 新線程()

作為完整 class 的變量,而不僅僅是內部方法

這應該可以解決問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM