Мне нужна помощь с уведомлением для медиаплеера, а также чтобы он не переставал воспроизводить музыку через 5 минут при выключенном экране.
Я пробовал читать много постов, но у меня просто нет навыковпока что он работает в моем приложении, которое я собрал из примеров.
Будет полезна некоторая помощь.
Спасибо
Манифест
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.hypedem.app">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.PARTIAL_WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity
package com.hypedem.app;
import android.os.PowerManager;
import android.provider.Settings;
import android.webkit.WebSettings;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import wseemann.media.FFmpegMediaMetadataRetriever;
import static com.google.android.exoplayer2.offline.DownloadService.startForeground;
public class MainActivity extends AppCompatActivity implements AudioManager.OnAudioFocusChangeListener {
private String nowPlaying;
private ImageView playStopBtn;
private SimpleExoPlayer player;
private AudioManager audioManager;
private boolean isPlaying = false;
private TextView radioStationNowPlaying;
private String streamUrl = Config.STREAMING_URL;
private static final int READ_PHONE_STATE_REQUEST_CODE = 22;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
playStopBtn = findViewById(R.id.playStopBtn);
radioStationNowPlaying = findViewById(R.id.radioStationNowPlaying);
initExoPlayer();
processPhoneListenerPermission();
BroadcastReceiver 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 (isPlaying) {
stop();
playStopBtn.setImageResource(R.drawable.ic_play);
}
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(broadcastReceiver, filter);
if (Config.IS_LOADING_NOW_PLAYING) {
Thread t = new Thread() {
public void run() {
try {
while (!isInterrupted()) {
runOnUiThread(() -> reloadShoutCastInfo());
Thread.sleep(20000);
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
}
private void initExoPlayer() {
DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
AdaptiveTrackSelection.Factory trackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
DefaultTrackSelector trackSelector = new DefaultTrackSelector(trackSelectionFactory);
player = ExoPlayerFactory.newSimpleInstance(getApplicationContext(), trackSelector);
}
public void play(String channelUrl) {
if (isNetworkAvailable() && requestFocus()) {
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(getApplicationContext(), "Simplicity Web Design Player");
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).setExtractorsFactory(extractorsFactory).createMediaSource(Uri.parse(channelUrl));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
isPlaying = true;
playStopBtn.setImageResource(R.drawable.ic_pause);
} else {
Toast.makeText(this, "No internet", Toast.LENGTH_SHORT).show();
playStopBtn.setImageResource(R.drawable.ic_play);
}
}
public void stop() {
player.setPlayWhenReady(false);
player.stop();
isPlaying = false;
playStopBtn.setImageResource(R.drawable.ic_play);
}
private void reloadShoutCastInfo() {
if (isNetworkAvailable()) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
isPlaying = false;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void playStop(View view) {
if (!isPlaying) {
play(streamUrl);
} else {
stop();
}
}
private void processPhoneListenerPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, READ_PHONE_STATE_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == READ_PHONE_STATE_REQUEST_CODE) {
if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(getApplicationContext(), "Permission not granted.\nWe can't pause music when phone ringing without this permission.", Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
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
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", (dialog, id) -> {
stop();
finish();
})
.setNegativeButton("No", (dialog, id) -> dialog.cancel());
AlertDialog alert = builder.create();
alert.show();
}
private boolean requestFocus() {
return (audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED);
}
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS) {
stop();
finish();
}
}
@SuppressLint("StaticFieldLeak")
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(streamUrl);
nowPlaying = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ICY_METADATA).replaceAll("StreamTitle", "").replaceAll("[=,';]+", "");
mmr.release();
return null;
}
@Override
protected void onPostExecute(String result) {
radioStationNowPlaying.setText(nowPlaying);
}
}
public void openBrowser(View view){
//Get url from tag
String url = (String)view.getTag();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
//pass the url to intent data
intent.setData(Uri.parse(url));
startActivity(intent);
}
public void openWebsite(View v) {
//call window2
setContentView(R.layout.website);
}
public void openWindow2(View v) {
//call window2
setContentView(R.layout.window2);
WebView webView = (WebView) findViewById(R.id.webview2);
WebSettings webSettings = webView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("https://simplicitywebdesign.co.uk/hypedem/appinfo.htm");
}
public void openActivity_Main(View v) {
//call window2
setContentView(R.layout.activity_main);
}
public void openPermrequest(View v) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (!pm.isIgnoringBatteryOptimizations(getPackageName()))
{
// Prompt the user to disable battery optimization
Intent intent = new Intent();
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
startActivity(intent);
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/logoId"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="false"
android:contentDescription="@string/app_name"
android:scaleType="centerCrop"
android:src="@drawable/bg2"
android:visibility="visible" />
<ImageView
android:id="@+id/imageView"
android:layout_width="382dp"
android:layout_height="47dp"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="14dp"
android:layout_marginEnd="15dp"
android:layout_marginBottom="137dp"
android:clickable="true"
android:contentDescription="@string/img_simplicity"
android:focusable="true"
android:onClick="openBrowser"
android:tag="https://hypedem-radio.com/start-your-own-internet-radio-station/"
app:srcCompat="@drawable/button" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="31dp"
android:layout_height="26dp"
android:clickable="true"
android:contentDescription="@string/settings"
android:onClick="openWindow2"
android:visibility="visible"
app:srcCompat="@drawable/settings"
android:focusable="true" />
<ImageView
android:id="@+id/imageView4"
android:layout_width="match_parent"
android:layout_height="43dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="83dp"
android:clickable="true"
android:contentDescription="@string/goto_website"
android:focusable="true"
android:onClick="openBrowser"
android:tag="https://hypedem-radio.com/"
app:srcCompat="@drawable/web" />
<ImageView
android:id="@+id/playStopBtn"
android:layout_width="106dp"
android:layout_height="68dp"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="13dp"
android:layout_marginTop="339dp"
android:layout_marginEnd="292dp"
android:layout_marginBottom="6dp"
android:contentDescription="@string/image_content_description"
android:onClick="playStop"
android:src="@drawable/ic_play" />
<TextView
android:id="@+id/radioStationName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="375dp"
android:layout_marginBottom="35dp"
android:gravity="center"
android:text="@string/app_name"
android:textColor="@android:color/white"
android:textSize="24sp" />
<TextView
android:id="@+id/radioStationNowPlaying"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="15dp"
android:gravity="center"
android:text="@string/app_slogan"
android:textColor="@android:color/white"
android:textSize="14sp" />
<ImageView
android:id="@+id/stationLogo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="26dp"
android:layout_marginBottom="24dp"
android:contentDescription="@string/image_content_description"
android:src="@drawable/ic_logo" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000" />
</RelativeLayout>