Android Mediaplayer Streaming - Worked now it doesn't - java

I have a strange problem. I have an mp3 stream I am trying to utilize within an application (2.1). Before you say streaming isn't supported here, it seems to be.
I was able to get it working last night by using the following code:
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Stream extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("http://ipaddress:8000/");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
However, today, it doesn't work. Furthermore, last night -- I was able to use the Internet Browser on my android phone to stream it. Although, last night when I went to the address, it opened the stream in video player. Nonetheless, I am unable to open it today in the browser, either.
In the browser, I keep getting the "page not displayed" page. I have actually verified it is online. I can browse to it from my PC (on the same network), and have confirmed internet connectivity to my android by utilizing other streaming applications and browsing to other web pages.
I am stumped as to why my code (or the stream) suddenly stopped working overnight on the phone. The code even works on a 2.1 emulator (and streams it).
Let me know what you all think, please.
Thanks in advance!

Seems to be a connectivity problem on the network side. Too many connections were opened from the phone on WiFi to the streaming server. This caused an IP blacklist. Today, this seems to have cleared up.

Related

How to get Google Ad Id in android Java

I am trying to get the google ad id (GAID)in android java but I am getting exeception like:
androidx.ads.identifier.AdvertisingIdNotAvailableException: No compatible AndroidX Advertising ID Provider available.
My Code
ListenableFuture<AdvertisingIdInfo> adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
System.out.println("adinfo"+adInfo.toString());
try {
String id = adInfo.get().getId();
System.out.println("adod"+id);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
And dependienced i added
implementation 'com.google.android.gms:play-services-ads:19.4.0'
implementation 'androidx.ads:ads-identifier:1.0.0-alpha04'
In Manifest I added
<meta-data
android:name="com.google.android.gms.ads.AD_MANAGER_APP"
android:value="true"/>
I have tried many solutions but it is not useful. Please help me out to solve the issue.
The gaid dependency in androidx seems to be at fault.
Many people (including me) have followed Google's ad ID documentation and have reported the same issue. Also, Google's documentation on this matter appears outdated since the examplatory code snippet is wrong (e.g. function addCallback is missing a parameter).
The solution is to add this dependency in your gradle file instead of the ones you mentioned:
implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
You can then fetch the advertising id this way:
AdvertisingIdClient.Info idInfo;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
String advertisingId = idInfo.getId();
//do sth with the id
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
}
If you want to use the id only when the user hasn't opted out of personalised ads, you can add this after retrieving the id info:
//if user hasn't opted out of ads in device settings
if(idInfo.isLimitAdTrackingEnabled()) {
//do sth with the id
}
Edit: The mentioned Google's documentation actually has a note that encourages you to use the ads identifier library I mentioned:

Unable to write to specified path in internal storage in android

I am trying to write to a specific path in internal storage in my android app :/data/somefolder
but I get the error java.io.filenotfoundexception : Permission denied
String testString="Hello World!";
File newFile=new File("/data/somefolder/testFile.txt");
try{
OutputStream myOut=new BufferedOutputStream(new FileOutputStream(newFile,true));
myOut.write(testString.getBytes());
myOut.flush();
myOut.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My question is : Is it even possible to write into this folder in android internal storage or does android restrict file creation only to the specific package like
/data/data/package/files ?
I tried using FileOutputStream and the file got created successfully in /data/data/package/files.
I don't think you can just write into the data dir. That would require root access. You can either use the apps internal storage or the external storage (SD card). Please see here how that works.

Why is there no InputManager.getInstance() for me? And injectInputEvent()?

I'm trying to develop a service that injects touch events to the system while the service interacts with some hardware/remote server. I've googled and everyone suggests using the InputManager class, referencing Monkey as an example project to follow.
However, there is no getInstance() method for me in InputManager! All I have access to is exactly what the documentation shows. No getInstance() method, and most importantly, no injectInputEvent() method.
My build target SDK is Android 4.1.2, and my AndroidManifest.xml file specifies a target SDK version of 16 (I've tried changing the min target to 16 too, which didn't help (plus I'd like to keep it at 8 if possible)).
How on earth can I use InputManager like Monkey does? Where are the methods Monkey is using, and why can't I use them?
You cannot inject input events to one application from other application. Also you cannot inject events to your own application from within application. https://groups.google.com/forum/?fromgroups=#!topic/android-developers/N5R9rMJjgzk%5B1-25%5D
If you want to automate, you can use monkeyrunner scripts to do the same.
Class cl = InputManager.class;
try {
Method method = cl.getMethod("getInstance");
Object result = method.invoke(cl);
InputManager im = (InputManager) result;
method = cl.getMethod("injectInputEvent", InputEvent.class, int.class);
method.invoke(im, event, 2);
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe this is a bit late but could be helpful for future reference.
Method 1: Using an instrumentation object
Instrumentation instrumentation = new Instrumentation();
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Method 2: Using internal APIs with reflection
This method uses reflection to access internal APIs.
private void injectInputEvent(KeyEvent event) {
try {
getInjectInputEvent().invoke(getInputManager(), event, 2);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
private static Method getInjectInputEvent() throws NoSuchMethodException {
Class<InputManager> cl = InputManager.class;
Method method = cl.getDeclaredMethod("injectInputEvent", InputEvent.class, int.class);
method.setAccessible(true);
return method;
}
private static InputManager getInputManager() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<InputManager> cl = InputManager.class;
Method method = cl.getDeclaredMethod("getInstance");
method.setAccessible(true);
return (InputManager) method.invoke(cl);
}
injectInputEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
injectInputEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Please note that method 1 is a clean solution based on public API and internally it uses the same calls from method 2.
Also note that neither of this two methods can be invoked from the MainThread.

Music in Java (start/stop)

Ok, so I am making a game and the music changes when you are in different regions or if there is an interruption, like with an AI.
So I have JUST learned how to make music showup in my program, and now I am trying to make it stop, but I am unsure how to, below is a snippet of code where the music plays and then I try to overwite it with new music when an action occurs.
public static void songs(String word) {
String temp = word;
if (temp.equals("start")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
} catch (IOException e) {
System.err.println(e);
}
}
if (temp.equals("stop")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/silence.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.stop(as);
System.out.println("stopping");
} catch (IOException e) {
System.err.println(e);
}
}
}
This is the only method I have been able to find that has the music play, but if you guys have any other suggestions please let me know.
Again, I want to have sound affects and music going, and right now all that happens is one song will play, and it will not stop under any circumstance until it hits the very end of its length. I want to be able to stop songs whenever a new one should come on, and also allow sound affects to pop up.
Thanks!
(since I am stuck on this and need an answer now I will probably repost on one or two more java sites so I can get a response ASAP, thank you though!!!!)
EDITED CODE: (still does not stop the current stream, any more suggestions appreciated)
public static void songs(String word) throws IOException {
String temp = word;
if (temp.equals("go")) {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
}
if (temp.equals("stop")) {
//don't try and do things with a null object!
if (as != null) {
AudioPlayer.player.stop(as);
System.out.println("stopping1");
}
System.out.println("stopping2");
AudioPlayer.player.stop(as);
}
}
Currently you're creating a new AudioStream in your stop branch and calling the stop method using this. This is a different object to the one that is currently playing. Try making the AudioStream a class variable, and calling stop on that instead.
EDIT: at the top of the class containing your code...
class YourClass {
//the class member variable
private AudioStream as;
//[etc...]
In your start branch:
// 'as' has already been defined above
as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
In your stop branch:
try
{
//don't try and do things with a null object!
if (as != null)
{
AudioPlayer.player.stop(as);
}
System.out.println("stopping");
}
catch (IOException e)
{
System.err.println(e);
}
You may have trouble with the static identifier on your method - if you're calling this from within an instantiated class you don't need this.
I can't even access these sun.audio Objects on my Eclipse IDE--I know they are in rt.jar, but there is header info about them being proprietary and such.
Can the Java Sound library (javax.sound.sampled) handle what you want to do? Both Clip and SourceDataLine allow one to stop playback. That is a more usual way of playing sound, if you want to use native Java.
Playback into is here:
http://docs.oracle.com/javase/tutorial/sound/playing.html
But the documentation, overall, is not exactly rich with examples. There's example code at this site
http://www.jsresources.org/
and plenty of people here who could help if you run into problems with the native Java approach.

Android TCP - program crashes

I cant seem to get a simple TCP connection going between a java server application and Android (I have tried both the emulator and the Android Dev Phone 2). I am getting this error on the Emulator "The application Data Receive (process com.mdog.datareceive) has stopped unexpectedly. Please try again."
Forgive me but I am very new to android. So I don't know how to debug it... but I am not trying anything too complex. Eventually I want to try and "consume" the bytes I am receiving in the application. and have the TCP run in the background... but for now simply getting the phone and computer to communicate would be great.
If you can help me that would be awesome.
Code for Android side:
public class Receive extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
Socket connectionSocket = null;
byte[] inputHolderByteArray = new byte[5*1024];
/* Connect to Server */
try {
connectionSocket = new Socket("192.168.0.104", 11313);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/* Send an s to server to start transmission */
try {
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
out.print('s');
out.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
/* read server transmission */
try {
connectionSocket.getInputStream().read(inputHolderByteArray);
} catch (IOException e) {
e.printStackTrace();
}
tv.setText("done");
setContentView(tv);
}
}
Each instance of the emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet.
The virtual router for each instance manages the 10.0.2/24 network address space — all addresses managed by the router are in the form of 10.0.2., where is a number. Addresses within this space are pre-allocated by the emulator/router.
You have to refer to the development machine with address as: 10.0.2.2 instead of 192.168.0.104 in your case. If you want to refer to another machine in your LAN, then you can Use Network Redirections
http://developer.android.com/guide/developing/tools/emulator.html#emulatornetworking
While superfell is correct that the full stack trace would help diagnose this, based on your code the/a likely problem is that you are breaking up every statement into it separate try/catch blocks. This probably isn't your core issue(my guess is you have a networking issue), but it is what is causing the system to crash.
Typically in Java, statements that are reliant on each other which can throw Exceptions are put in the same try/catch statement. What is most likely happening for you is that the code enters your first try catch block where you try to define a new socket. This fails throwing an exception like 'UnknownHostException'. connectionSocket remains null but the code enters the catch for UnknownHostException. You print the stack trace, but the program doesn't exit. Your code continues on to the following try/catch block where you call
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
This causes a NullPointerException. This is a RuntimeException which is not checked and, because it is unchecked, you are not forced to catch it in a catch statement. The exception now causes your VM to crash and causes the error screen you have reported.
So, even though getting the logcat stacktrace will tell us more about your issue, the code you have constructed should be condensed into a single try/catch statement since all code is dependent on the first try/catch completing without error.
Edit:
Try constructing your application like this
public class Receive extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
Socket connectionSocket = null;
byte[] inputHolderByteArray = new byte[5*1024];
/* Connect to Server */
try {
connectionSocket = new Socket("192.168.0.104", 11313);
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
out.print('s');
out.flush();
connectionSocket.getInputStream().read(inputHolderByteArray);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
tv.setText("done");
setContentView(tv);
}
}
When we say 'get the stacktrace', this means you need to connect to the emulator or device using the android debug bridge (adb) and a program called logcat. If you only have the emulator and no phone connected to your pc, try running the following:
adb logcat *:D
This will output the log information to the terminal. Leave this window open and run your application. You should see a stack trace get printed. Please take the time to get to know logcat and adb.

Categories

Resources