Commit ce066e4e authored by Kristo Oidermaa's avatar Kristo Oidermaa
Browse files

raadio versioon 1

parent 738a41c5
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.externalNativeBuild
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
<entry name="!?*.aj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
<component name="CopyrightManager">
<settings default="" />
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/volley" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
</list>
</value>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/KristoRadioPlayer.iml" filepath="$PROJECT_DIR$/KristoRadioPlayer.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/volley/volley.iml" filepath="$PROJECT_DIR$/volley/volley.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/volley" vcs="Git" />
</component>
</project>
\ No newline at end of file
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.example.kristo.kristoradioplayer"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.android.volley:volley:1.0.0'
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\Users\Kristo\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
package com.example.kristo.kristoradioplayer;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.kristo.kristoradioplayer", appContext.getPackageName());
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kristo.kristoradioplayer">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BackgroundMusicService">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</service>
</application>
</manifest>
\ No newline at end of file
package com.example.kristo.kristoradioplayer;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by Kristo on 10/11/2017.
*/
public class BackgroundMusicService extends Service implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnInfoListener {
private static final String TAG = BackgroundMusicService.class.getSimpleName();
RequestQueue requestQueue;
String url = "http://dad.akaver.com/api/songtitles/SP";
String artist;
String songTitle;
private MediaPlayer mediaPlayer;
private String streamUrl;
private ScheduledExecutorService scheduleTaskExecutor;
private BroadcastReceiver mBroadcastReceiver;
TelephonyManager telephonyManager;
PhoneStateListener phoneStateListener;
boolean onCall = false;
@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
Log.v(TAG, "onStartCommand");
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnInfoListener(this);
try {
streamUrl = intent.getStringExtra("streamUrl");
mediaPlayer.setDataSource(streamUrl);
} catch (IOException e) {
e.printStackTrace();
}
startMediaPlayer();
startArtistInfo();
phoneCallManager();
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "mBroadcastReceiver.stopPlayer - broadcast");
if (intent.getAction().equals(Constants.PLAYER_INTENT_STATUS_STOP_PLAYER)) {
stopMediaPlayer();
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constants.PLAYER_INTENT_STATUS_STOP_PLAYER);
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, intentFilter);
return Service.START_REDELIVER_INTENT;
}
private void phoneCallManager() {
telephonyManager = (TelephonyManager) getSystemService(getBaseContext().TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.v(TAG, "Phone ringing, need to stop playback");
onCall = true;
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.v(TAG, "Phone offhook, need to stop playback");
onCall = true;
mediaPlayer.stop();
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.v(TAG, "Phone now idle, resuming playing");
if (onCall) {
mediaPlayer.prepareAsync();
}
onCall = false;
break;
}
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private void startArtistInfo() {
scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
new getArtistInfo().execute();
}
}, 0, 15, TimeUnit.SECONDS);
}
private void startMediaPlayer() {
Intent intent = new Intent(Constants.PLAYER_INTENT_STATUS_BUFFERING);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
mediaPlayer.prepareAsync();
}
private void stopMediaPlayer() {
Intent intent = new Intent(Constants.PLAYER_INTENT_STATUS_STOPPED);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
scheduleTaskExecutor.shutdownNow();
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
Log.v(TAG,"onStopMediaPlayer");
stopSelf();
} catch (Exception e) {
e.printStackTrace();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "IBinder");
return null;
}
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
Intent intent = new Intent(Constants.PLAYER_INTENT_STATUS_PLAYING);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
mediaPlayer.start();
}
@Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
private class getArtistInfo extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
requestQueue = Volley.newRequestQueue(getBaseContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("SongHistoryList");
JSONObject songInfoObject = jsonArray.getJSONObject(0);
artist = songInfoObject.getString("Artist");
songTitle = songInfoObject.getString("Title");
Intent intent = new Intent(Constants.PLAYER_INTENT_STATUS_TEST);
intent.putExtra(Constants.PLAYER_INTENT_STATUS_ARTIST_NAME, artist);
intent.putExtra(Constants.PLAYER_INTENT_STATUS_SONG_TITLE, songTitle);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
} catch (Exception e) {
Log.v(TAG, "JSON array error" + e.toString());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "Volley error");
}
}
);
requestQueue.add(jsonObjectRequest);
return null;
}
}
}
package com.example.kristo.kristoradioplayer;
public class Constants {
public static final int PLAYER_STATUS_STOPPED = 0;
public static final int PLAYER_STATUS_BUFFERING = 1;
public static final int PLAYER_STATUS_PLAYING = 2;
public static final String PLAYER_INTENT_STATUS_STOPPED = "com.example.kristo.player-status-stopped";
public static final String PLAYER_INTENT_STATUS_BUFFERING = "com.example.kristo.player-status-buffering";
public static final String PLAYER_INTENT_STATUS_PLAYING = "com.example.kristo.player-status-playing";
public static final String PLAYER_INTENT_STATUS_TEST = "com.example.kristo.player-status-test";
public static final String PLAYER_INTENT_STATUS_STOP_PLAYER = "com.example.kristo.player-status-stop-player";
public static final String PLAYER_INTENT_STATUS_ARTIST_NAME = "com.example.kristo.player-status-artist-name";
public static final String PLAYER_INTENT_STATUS_SONG_TITLE = "com.example.kristo.player-status-song-title";
}
package com.example.kristo.kristoradioplayer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Button mButton;
private TextView mTextViewPlayerStatus;
private TextView mSongTitle;
private int mPlayerStatus = Constants.PLAYER_STATUS_STOPPED;
private BroadcastReceiver mBroadcastReceiver;
private AudioManager audioManager;
private SeekBar seekBarVolume;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "OnCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
setSeekBar();
mButton = (Button) findViewById(R.id.buttonPlayStop);
mTextViewPlayerStatus = (TextView) findViewById(R.id.textViewPlayerStatus);
mSongTitle = (TextView) findViewById(R.id.songTitle);
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "mBroadcastReceiver.onReceive");
switch (intent.getAction()) {
case Constants.PLAYER_INTENT_STATUS_PLAYING:
mPlayerStatus = Constants.PLAYER_STATUS_PLAYING;
Log.v(TAG, "playing");
mButton.setText("Stop");
break;
case Constants.PLAYER_INTENT_STATUS_TEST:
String artist = intent.getStringExtra(Constants.PLAYER_INTENT_STATUS_ARTIST_NAME);