I cant connect to the server i dont know why please help me. This is my code :
public class Sample extends Activity{
/** Called when the activity is first created. */
TextView tvHello;
XMPPTCPConnection connection;
ConnectionConfiguration config;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvHello = (TextView) findViewById(R.id.tvHello);
Log.i("ohyeah", "I'm here");
config = new ConnectionConfiguration("host", 5222, "servername");
connection = new XMPPTCPConnection(config);
try {
connection.connect();
// tvHello.setText("Connected to XMPP server");
Log.i("ohyeah", "Successfully Connected");
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ohyeah", "Not Connected");
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "Something Fishy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "yes");
}
}
}
this is my error:
http://i.stack.imgur.com/iaRdO.png
You can not do long or background running process in ui thread so try to use AsyncTask to connect xmpp server :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvHello = (TextView) findViewById(R.id.tvHello);
Log.i("ohyeah", "I'm here");
connectToXmppServer();
}
public void connectToXmppServer(){
new AsyncTask<Void,Void,String>(){
#Override
protected String doInBackground(Void... params) {
config = new ConnectionConfiguration("host", 5222, "servername");
connection = new XMPPTCPConnection(config);
try {
connection.connect();
// tvHello.setText("Connected to XMPP server");
Log.i("ohyeah", "Successfully Connected");
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ohyeah", "Not Connected");
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "Something Fishy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ohyeah", "yes");
}
return null;
}
}.execute();
}
Related
I have an App that is receiving a video file from another App that is working as a Server. While the App is saving the file received on the socket, the video stream starts playing the file (which is under construction). In the code sample, after I press the btnStream, I press the btnPlay and App runs successfully. However, if the playing rate is greater than the download rate, an error will occur. I want to avoid this case. So I need to have a listener on the Video Playing that will pause the videoview when it predicts that this error will occur. I know a solution where if I know the video size, I can counter the bytes received and monitor how many seconds have been buffered and see if the videoview should pause or not. However, is it possible to do it without knowing the video file size? Or having two threads that depends on each other? Thanks.
Note: the VideoView used is a custom one where it can play FileDescriptor.
btnStream.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = etURL.getText().toString();
String ip = "10.0.0.24";
int port = 7878;
mct= new VideoDownloadTask(ip,port);
mct.execute();
}});
final MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(mVideoView);
Button btnPlay = (Button) findViewById(R.id.button2);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mVideoView.setVideoFD((new FileInputStream(new File("/sdcard/tempVideo.mp4")).getFD()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mVideoView.seekTo(0);
mVideoView.start();
}
});
}
public class VideoDownloadTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
Socket socket=null;
VideoDownloadTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(InetAddress.getByName(dstAddress), dstPort);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
if(socket!=null)socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
File f = new File("/sdcard/tempVideo.mp4");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in=null;
try {
in = new DataInputStream (socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream videoFile = null;
try {
videoFile = new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int len;
byte buffer[] = new byte[8192];
try {
while((len = in.read(buffer)) != -1) {
videoFile.write(buffer, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
videoFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Done Downloading File",
Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
}
I applied a simple solution that resolved the problem. I am sharing it if anyone is having the same problem. The solution was simply to add an error listener to the videoView that will block the error popups and pauses the video.
mVideoView.setOnErrorListener(new OnErrorListener(){
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
statusText.setText("ERROR PLAYING VIDEO");
mVideoView.pause();
return true;
}
});
pDialog = new ProgressDialog(PlayVideoActivity.this);
pDialog.setTitle("Gajacharitra");
pDialog.setMessage("Buffering video...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
try {
// Start the MediaController
mediacontroller.setAnchorView(mVideoView);
// Get the URL from String VideoURL
Uri video = Uri.parse(mVideoURL);
mVideoView.setMediaController(mediacontroller);
mVideoView.setVideoURI(video);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
mVideoView.start();
}
});
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
mVideoView.pause();
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
return true;
}
});
} catch (Exception e) {
/*Log.e("Error", e.getMessage());
e.printStackTrace();*/
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
}
I am unable to fetch linkedin connection details;i am able to fetch only default details like first and last name,id etc.but i want to fetch connections dob,email etc..
share = (Button) findViewById(R.id.share);
name = (TextView) findViewById(R.id.name);
et = (EditText) findViewById(R.id.et_share);
login = (Button) findViewById(R.id.login);
photo = (ImageView) findViewById(R.id.photo);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
linkedInLogin();
}
});
// share on linkedin
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>"+ share +"</comment><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void linkedInLogin() {
ProgressDialog progressDialog = new ProgressDialog(
LinkedInSampleActivity.this);
LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,
progressDialog);
d.show();
// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getToken());
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getTokenSecret());
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName()+"DOB"+p.getDateOfBirth());
name.setVisibility(0);
login.setVisibility(4);
share.setVisibility(0);
et.setVisibility(0);
userConnections();
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
private void userConnections() {
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
**ProfileField.DATE_OF_BIRTH,**
ProfileField.PHONE_NUMBERS
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
System.out.println("connections name"+person.getFirstName()+" "+person.getLastName()+":"+**person.getDateOfBirth()**+person.getId());
itemslist.add(person);
}
System.out.println("person arraylist count of my connections"+itemslist.size());
}
});
// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
I tried to fetch date of birth of my connections,but its showing null in the position..
D.O.B. isn't a field you can get for a connection. Please read the documentation - "For 1st degree connections, you may only retrieve profile fields available with the r_basicprofile member permission"
https://developers.linkedin.com/documents/connections-api
UPDATE: ok so I kept trying to press send until I received the java.net.SocketException: sendto failed: EPIPE (Broken pipe) exception as a toast message once and then there was no activity once again when I pressed the send button. Meaning I didn't get the exception again.
I have two apps where one acts as the server and the other as a client. I was able to send a message from the server to the client like this
dataOutputStream.writeUTF("hello");
basically as a hardcoded string
but when I added a textfield and a button to the server app and tried listening to the onClick like this
sendChatbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
dataOutputStream.writeUTF(chatMsg);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
}
}
});
Absolutely NOTHING happened when I press the SEND button and the client did not receive any message, I don't even get any exception as a toast. By the way I am able to send messages from the client to the server and the server receives the client's messages but the client doesn't get any messages from the server.
The logcat although shows this:
08-09 04:13:45.694: E/LocSvc_adapter(761): E/virtual loc_api_adapter_err LocApiV02Adapter::injectPosition(double, double, float):632]: error! status = eLOC_CLIENT_FAILURE_INVALID_PARAMETER, inject_pos_ind.status = UNKNOWN
08-09 04:15:25.220: A/ActivityManager(761): Service ServiceRecord{42e78d58 u0 com.estrongs.android.pop/com.estrongs.android.ui.notification.ESTaskService} in process ProcessRecord{449c4320 9734:com.estrongs.android.pop/u0a245} not same as in map: null
08-09 04:16:06.444: E/AudioStreamOutALSA(269): PCM_Write set_amp_mode,1
Here's my Server code:
public class ServerActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
EditText chatBoxText;
Button sendChatbtn, startGameBtn;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_socket);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
chatBoxText=(EditText) findViewById(R.id.chatBox);
sendChatbtn=(Button) findViewById(R.id.sendChatButton);
startGameBtn=(Button) findViewById(R.id.startGamebutton);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
closeSockets();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
String chatMsg = chatBoxText.getText().toString();
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
ServerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
String messageFromClient = "";
//If no message sent from client, this code will block the program
messageFromClient = dataInputStream.readUTF();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
ServerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
sendChatbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
dataOutputStream.writeUTF(chatMsg);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
}
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
final String errMsg = e.toString();
ServerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(errMsg);
}
});
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
return ip;
}
public void closeSockets()
{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
Here's the Client Code:
public class ClientActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
EditText welcomeMsg;
private MyClientTask myClientTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
editTextAddress = (EditText) findViewById(R.id.address);
editTextPort = (EditText) findViewById(R.id.port);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
textResponse = (TextView) findViewById(R.id.response);
welcomeMsg = (EditText)findViewById(R.id.welcomemsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textResponse.setText("");
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
String tMsg = welcomeMsg.getText().toString();
if(tMsg.equals("")){
tMsg = null;
Toast.makeText(ClientActivity.this, "No Welcome Msg sent", Toast.LENGTH_SHORT).show();
}
MyClientTask myClientTask = new MyClientTask(editTextAddress
.getText().toString(), Integer.parseInt(editTextPort
.getText().toString()),
tMsg);
myClientTask.execute();
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String msgToServer;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
if(msgToServer != null){
dataOutputStream.writeUTF(msgToServer);
}
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
return null;
}
protected void CloseSockets()
{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
protected void onDestroy()
{
myClientTask.CloseSockets();
super.onDestroy();
}
}
You are not updating the chatMsg string after the onClick, so it initializes as a zero length string, and does not change.
When onClick occurs, you need to get the current string from your TextView:
#Override
public void onClick(View v) {
// add this!!!
chatMsg = chatBoxText.getText().toString();
try {
dataOutputStream.writeUTF(chatMsg);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ServerActivity.this, "An exception occurred: " + e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
}
}
android cannot connect MYSQL server
Error Note:
04-11 04:01:51.283: W/System.err(913): com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
04-11 04:01:51.296: W/System.err(913): The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
04-11 04:01:51.296: W/System.err(913): at java.lang.reflect.Constructor.constructNative(Native Method)
04-11 04:01:51.304: W/System.err(913): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
MYSQL-DB Connection Code
private String CONNECTION_URL = "jdbc:mysql://192.168.2.10:8090/test";
private String user;
private String pass;
private java.sql.Statement stmt;
private java.sql.Connection conn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "step 1");
try {
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Log.e(TAG, "step 2");
} catch (InstantiationException e) {
Log.e(TAG, "Error 1");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e(TAG, "error 2");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
Log.e(TAG, "error 3");
// TODO Auto-generated catch block
e.printStackTrace();
}
try {Log.e(TAG, "step 3");
conn = DriverManager.getConnection(CONNECTION_URL, user, pass);
} catch (SQLException e) {
Log.e(TAG, "error 4");
// TODO Auto-generated catch block
e.printStackTrace();
}
try {Log.e(TAG, "step 4");
stmt = conn.createStatement();
} catch (SQLException e) {Log.e(TAG, "error 5");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am trying to start browser action using Intent.ACTION_VIEW in onPostExecute() method of AsyncTask Class. But it is failing and giving below error
03-18 17:48:55.721: E/AndroidRuntime(26997): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
And when I add FLAG_ACTIVITY_NEW_TASK before startActivity() it doesn't crash but also no
action happens. Below is my code :
How to overcome this issue. Is this Context issue ?
private static class Task extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
CheckIfCertificateAvailable();
return null;
}
public void CheckIfCertificateAvailable() {
//Check for CertiDownload, OpenCerti, DeleteCerti & DeleteDirectory to be run only once when App installs for the first time
KeyStore ks = null;
try {
ks = KeyStore.getInstance("AndroidCAStore");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ks.load(null, null);
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Enumeration aliases = null;
try {
aliases = ks.aliases();
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement().toString();
X509Certificate cert = null;
try {
cert = (X509Certificate)
ks.getCertificate(alias);
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(cert.getSubjectDN().getName().contains("CN=vpn.origin.mediainsiderspanel.com,OU=IT,O=Symphony AM,L=PA,ST=CA,C=US")){
prefs.setCertiStatus(context, false);
Log.d("DManager", "Certificate already exist no installation required - Flag False");
break;
}
else
{
prefs.setCertiStatus(context, true);
Log.d("DManager", "Certificate does not exist will have to install - Flag True");
}
}
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//prefs.setCertiStatus(context, prefs.getCertiStatus(context));
Log.d("DManager", "onPostExecute - Flag : " + prefs.getCertiStatus(context));
if(prefs.getCertiStatus(context)){
Log.d("DManager", "Now Installing");
Uri uri = Uri.parse("http:url");
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setData(uri);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
else {
Log.d("DManager", "Return");
return;
}
super.onPostExecute(result);
}
}