I made a basic server in eclipse:
Server server;
int tcp = 8885, udp = 8885;
public ServerMain() {
server = new Server();
server.addListener(new Listener() {
public void connected(Connection c) {
System.out.println("Connection made");
}
public void received(Connection c, Object p) {
}
public void disconnected(Connection c) {
System.out.println("Disconnection made");
}
});
server.start();
try {
server.bind(tcp, udp);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ServerMain();
}
Then I created my client in android studio. I installed the library correctly. (According to google) I put the Kryonet jar into the libs folder and then rebuilt the project. I could then use Kryonet classes. Here is my code for my client:
Client client;
String ip = "MY.IP.ADDRESS";
int tcp = 8885, udp = 8885;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "Start");
client = new Client();
client.addListener(new Listener() {
public void received(Connection c, Object p) {
}
});
client.start();
try {
client.connect(5000, ip, tcp, udp);
Log.i(TAG, "conected");
} catch(IOException e) {
Log.i(TAG, "Error: " + e.getMessage());
}
}
It's the exact same code I would use in a normal Java client except now it's running directly from my android device. I get this error:
Error: Unable to connect to: /MY.IP.ADDRESS:8885
It cannot connect to my IP even though I port forwarded it and all. Why won't it connect? I have read online to add in this to my manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
So, I did:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Still to absolutely no avail. What am I doing wrong? (P.S. I have tried with both my network IP, and my public IP. I have no idea what I'm doing wrong, everything works fine with a normal Java program, but with an android app it bugs out.)
Try this code, it's working:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "Start");
client = new Client();
client.addListener(new Listener() {
public void received(Connection c, Object p) {
}
});
client.start();
new ConnectToServer.execute();
}
public class ConnectToServer extends AsyncTask<String, int[], String>
{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
client.connect(5000, ip, tcp, udp);
Log.i(TAG, "conected");
} catch(IOException e) {
Log.i(TAG, "Error: " + e.getMessage());
return null;
}
}
}
Related
Every HTTP request throws failed to connect to Server wherever App goes in sleep or minimize mode. This only happens in Android Pie(9.0).
Please check my code below,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncReadConfig asyncReadConfig = new AsyncReadConfig();
asyncReadConfig.execute();
}
});
}
class AsyncReadConfig extends AsyncTask<Integer, Integer, Object> {
#Override
protected Object doInBackground(Integer... integers) {
try {
return callGetURLService(CONFIGURATION_URL);
} catch (Exception e) {
return e;
}
}
}
private Object callGetURLService(String path) {
try {
URL url = new URL(path);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String text;
StringBuilder configParams = new StringBuilder();
while ((text = in.readLine()) != null) {
configParams.append(text);
}
JSONObject jsonObject = new JSONObject(configParams.toString());
//Doing my stuff
return null;
} catch (Exception e) {
e.printStackTrace();
}
}
In my manifeast.xml,
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:networkSecurityConfig="#xml/network_security_config"
.
.
In network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">MY_DOMAIN</domain>
</domain-config>
</network-security-config>
I'm just reading text file from server in sleep mode and I'm getting error,
java.net.ConnectException: Failed to connect to server
And as I'm switching my App from minimize mode to active mode, everything is working fine.
When your app is in the background you cant make network calls unless you are using a Foreground service to make the network call
I'm trying to create a service with an IPC connection defined in an .aidl file.
The service starts and the service connection can bind to it, but when the IPC API is called from the same thread it causes a NullPointerException.
When the call to the IPC API is put in an event on a button press it works.
How can this be fixed so that the call can be done without having a button event to start it.
My MainActivicty
public class MainActivity extends AppCompatActivity {
public final String TAG = "Main Activity";
IMyAidlInterface iMyAidlInterface;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
iMyAidlInterface = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent interFaceServiceIntent = new Intent(this, IMyAidlService.class);
bindService(interFaceServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
Intent sigGenIntent = new Intent(this, signalGenerator.class);
startService(sigGenIntent);
Button b = findViewById(R.id.button);
/*
* The following block is what I want to be able to execute. Currently it causes * a NullPointerException
* Caused by: java.lang.NullPointerException: Attempt to invoke interface method * 'int com.aidltest.IMyAidlInterface.getPid()' on a null object reference
*/
try {
iMyAidlInterface.getPid();
} catch (RemoteException e) {
e.printStackTrace();
}
/*
* The block below using the same interface from within a button event works
* without problem.
*/
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
iMyAidlInterface.getPid();
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
For reference my Aidl:
package com.aidltest;
interface IMyAidlInterface {
int getPid();
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
And my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aidltest">
<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=".IMyAidlService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
This is happening because iMyAidlInterface is null in your onCreate call. It is not set until your connection listener calls you back via onServiceConnected. Binding is an async operation.
I am trying to implement a telnet client in android that is going to continuously read data from a telnet server. I have verified that the server is sending data continuously by connecting to it from a telnet app from play store.
Now im trying to create an app to do the same and display the data on the screen using apache telnetclient. I have successfully connected to the telnet server, and I am able to read the correct lines for 5-10 seconds. The code is posted below.
What works:
Connecting to server.
Reading some lines for 5-10 seconds before the stream stops.
The problem:
The reading seems to stop after around 5-10 seconds, and hangs on readLine() with no new data coming in. Is this a problem with the code? Any help would be appreciated!
UPDATE:
I am trying to run this on an Android 4.2.2 device. I tried it on a newer android 7 device just now, and the code works as intended, I get continuous readings. Is there something in the android version that can be causing this?
--
This is the TestTelnetClient.class
public class TestTelnetClient extends Activity {
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private String server = "192.168.36.105";
TextView outputView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputView = (TextView)findViewById(R.id.output);
}
public void sendTelnet(View view) {
TelnetRead telnetRead = new TelnetRead();
telnetRead.execute();
}
private class TelnetRead extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
// Connect to the specified server
telnet.connect(server, 8110);
// Get input and output stream references
in = telnet.getInputStream();
//out = new PrintStream(telnet.getOutputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String aad = r.readLine();
while (true) {
publishProgress(aad);
aad = r.readLine();
}
//telnet.disconnect();
//finish();
//return aad;
//return "exit";
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
try {
outputView.setText(result);
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
#Override
protected void onPreExecute() {
}
//#Override
protected void onProgressUpdate(String... result) {
outputView.setText(result[0]);
}
}
This is the android manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"/>
<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=".TestTelnetClient"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I've rooted Nexus phone with lollipop. I'm trying to record incoming & outgoing calls.
My application extends DeviceAdminReceiver with policy of <force-lock />
I'm able to create the file with size > 0bytes. But when I play it, it is blank.
Please take a look at the code below:
Manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
.....
<service android:name=".RCService"
android:exported="false" >
</service>
.....
<receiver
android:name=".utils.MyDeviceAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<intent-filter>
<!-- This action is required -->
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
</intent-filter>
<!-- This is required this receiver to become device admin component. -->
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/device_admin" />
</receiver>
<receiver android:name=".CallRecoderBroadcast">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
device_admin.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
CallRecoderBroadcast.java
/**
* Lifecycle :
* Incoming call : RINGING -> OFFHOOK -> IDLE
* Outgoing Call : OFFHOOK -> IDLE
*/
public class CallRecoderBroadcast extends BroadcastReceiver {
private static final String TAG = "CallRecoderBroadcast";
private static final String ACTION_PHONE = "android.intent.action.PHONE_STATE";
private static final String OUTGOING_CALL = "android.intent.action.NEW_OUTGOING_CALL";
private static Boolean mCallOnGoing = Boolean.FALSE;
private MediaRecorder mRecorder = new MediaRecorder();
// private File mFile = null;
private String mNumber;
#Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals(ACTION_PHONE)) {
Bundle bundle = intent.getExtras();
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
Log.e(TAG, state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Log.e(TAG, bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER));
mNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (!mCallOnGoing) {
recordCall(context);
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
if (mCallOnGoing) {
stopRecording();
}
}
} else if (intent.getAction().equals(OUTGOING_CALL)) {
Log.e(TAG, "OUTGOING cALL");
Log.e(TAG, intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
mNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
private void recordCall(Context context) throws IOException, CustomExcpetion {
File file = prepareFile(context);
if (file.exists()) {
mCallOnGoing = Boolean.TRUE;
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(file.getAbsolutePath());
mRecorder.prepare();
mRecorder.start();
}
}
private void stopRecording() {
mCallOnGoing = Boolean.FALSE;
// mRecorder.stop();
mRecorder.release();
}
private File prepareFile(Context context) throws CustomExcpetion {
File outputFile = null;
try {
File dir = new File(context.getFilesDir(), "recorderdFiles");
if (!dir.exists()) {
dir.mkdirs();
}
Long timeStamp = System.currentTimeMillis();
outputFile = new File(dir, timeStamp.toString());
if (!outputFile.exists()) {
outputFile.createNewFile();
}
} catch (IOException exp) {
throw new CustomExcpetion(context, exp);
}
return outputFile;
}
}
P.S. - I've also tried with example given here, but it only working form Mic & not for uplink & downlink at the same time.
Unfortunately, voice call recorder is not supported on that device,
I think that will work fine on other devices.
I have this simple code, that makes a get to a webservice.
For some reason it cant connect and gives the error in the log unknownHostException
This is the code:
String URL = "http://services.sapo.pt/EPG/GetChannelList";
String result = "";
final String tag = "Data received: ";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
callWebService();
}
});
} // end onCreate()
public void callWebService(){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
}
This is part of my manifest
<permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidApp"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I found the solution.
I putted the internet permission using the GUI in manifest which added the tag
< permission android:name"android.permission.INTERNET"/>
Then by hand, i putted the correct tag that is:
< uses-permission android:name="android.permission.INTERNET" />
which is a different tag and it worked. GUI fail.
Not sure if you have already checked this, but please check if you are behind a proxy or firewall. Here is a way to configure the HttpClient for a proxy and official apache documentation.