How to start ACTION_VIEW in onPostExecute method of AsyncTask - java

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);
}
}

Related

VideoView Playing a file while it is received via socket

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();
}

Error in Asmack Android Connection to Server Xmpp

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();
}

UI thread runs before async class runs in android

I am doing a validation for fields in an android form.I am checking with server whether the username is available in the server or not.But the main thread goes to the next page before the async checking completes.
The code:
btnnext1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
isallValid=true;
//check second time for username validation(first time was in onfocus changed)
// if(txtusername.getText().toString().trim().equals("achuthan")){
// txtusername.setError("Username exsists!");
// isUsernameValid=false;
// }
//
// else
// {
// isUsernameValid=true;
// }
try {
Void async_result=new validateusername().execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(txtfullname.getText().toString().trim().length()==0)
{
txtfullname.requestFocus();
txtfullname.setError("Field required");
isallValid=false;
}
if(txtdob.getText().toString().trim().length()==0)
{
txtdob.requestFocus();
txtdob.setError("Field required");
isallValid=false;
}
if(txtoccupation.getText().toString().trim().length()==0)
{
txtoccupation.requestFocus();
txtoccupation.setError("Field required");
isallValid=false;
}
if(txtusername.getText().toString().trim().length()<6){
txtusername.requestFocus();
txtusername.setError("Minimum length of 6 characters");
isallValid=false;
}
if(txtpassword.getText().toString().trim().length()==0)
{
txtpassword.requestFocus();
txtpassword.setError("Field required");
isallValid=false;
}
if(txtconfirmpassword.getText().toString().trim().length()==0)
{
txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Field required");
isallValid=false;
}
else if(!txtpassword.getText().toString().trim().equals(txtconfirmpassword.getText().toString().trim()))
{
//txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Passwords not equal");
txtpassword.setError("Passwords not equal");
isallValid=false;
}
if(isallValid&&isUsernameValid)
{
//Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();
int id=radiogender.getCheckedRadioButtonId();
RadioButton rb=(RadioButton) view.findViewById(id);
String gender=rb.getText().toString();
((SignUpPage)getActivity()).getValues().gender=gender;
int id1=radiomarital.getCheckedRadioButtonId();
RadioButton rb1=(RadioButton) view.findViewById(id1);
String marital_status=rb1.getText().toString();
((SignUpPage)getActivity()).getValues().marital_status=marital_status;
((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();
((SignUpPage)getActivity()).selectFragment(1);
}
//if all valid , store values and go to next fragment
//((SignUpPage)getActivity()).selectFragment(1);
}
});
return view;
}
The async class:
public class validateusername extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username",txtusername.getText().toString().trim()));
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httppost);
result=responsetostring.getResponseBody(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result1) {
try {
jsonobj=new JSONObject(result);
job2=jsonobj.getJSONObject("server_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
finalresult=job2.getString("username_availability_message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(finalresult.equals("exist")){
txtusername.setError("Username exsists!");
isUsernameValid=false;
}
else if(finalresult.equals("available"))
{
isUsernameValid=true;
}
}
}
I tried using the get method so that the main thread waits till the async class finishes but it didnt work.Please help!!
Check isallValid only in button click , then Do this validation inside your onPostExecute(Void result) method,
if(isUsernameValid)
{
//Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();
int id=radiogender.getCheckedRadioButtonId();
RadioButton rb=(RadioButton) view.findViewById(id);
String gender=rb.getText().toString();
((SignUpPage)getActivity()).getValues().gender=gender;
int id1=radiomarital.getCheckedRadioButtonId();
RadioButton rb1=(RadioButton) view.findViewById(id1);
String marital_status=rb1.getText().toString();
((SignUpPage)getActivity()).getValues().marital_status=marital_status;
((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();
((SignUpPage)getActivity()).selectFragment(1);
}
now it will work.................
Do not use get() to call the AsyncTask, it hangs your UI.
So call your AsyncTask like,
String userName = txtusername.getText().toString().trim();
new validateusername().execute(userName); // pass the String from EditText, as you cannot interact with UI in doInBackground
Modify your AsyncTask like
public class validateusername extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username",arg0[0])); // arg0[0] is the username passed from AsyncTask call
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httppost);
result=responsetostring.getResponseBody(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result1) {
try {
jsonobj=new JSONObject(result);
job2=jsonobj.getJSONObject("server_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
finalresult=job2.getString("username_availability_message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(finalresult.equals("exist")){
txtusername.setError("Username exsists!");
isUsernameValid=false;
}
else if(finalresult.equals("available"))
{
isUsernameValid=true;
}
if(txtfullname.getText().toString().trim().length()==0)
{
txtfullname.requestFocus();
txtfullname.setError("Field required");
isallValid=false;
}
if(txtdob.getText().toString().trim().length()==0)
{
txtdob.requestFocus();
txtdob.setError("Field required");
isallValid=false;
}
if(txtoccupation.getText().toString().trim().length()==0)
{
txtoccupation.requestFocus();
txtoccupation.setError("Field required");
isallValid=false;
}
if(txtusername.getText().toString().trim().length()<6){
txtusername.requestFocus();
txtusername.setError("Minimum length of 6 characters");
isallValid=false;
}
if(txtpassword.getText().toString().trim().length()==0)
{
txtpassword.requestFocus();
txtpassword.setError("Field required");
isallValid=false;
}
if(txtconfirmpassword.getText().toString().trim().length()==0)
{
txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Field required");
isallValid=false;
}
else if(!txtpassword.getText().toString().trim().equals(txtconfirmpassword.getText().toString().trim()))
{
//txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Passwords not equal");
txtpassword.setError("Passwords not equal");
isallValid=false;
}
if(isallValid&&isUsernameValid)
{
//Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();
int id=radiogender.getCheckedRadioButtonId();
RadioButton rb=(RadioButton) view.findViewById(id);
String gender=rb.getText().toString();
((SignUpPage)getActivity()).getValues().gender=gender;
int id1=radiomarital.getCheckedRadioButtonId();
RadioButton rb1=(RadioButton) view.findViewById(id1);
String marital_status=rb1.getText().toString();
((SignUpPage)getActivity()).getValues().marital_status=marital_status;
((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();
((SignUpPage)getActivity()).selectFragment(1);
}
}
onPostExecute(), check the conditions and navigate to next activity.

android java play song, audio, sound file (external SD works but not internal storage)

External storage works, but not internal storage. Am I missing out on something fundamentally from the android storage mechanism?
thanks
public static void playSound()
{
//String path = internalPath + "/www/sounds/" + "SIREN.WAV"; // doesnt work
//String path = "file:///data/data/com.myproject.d08062014f/files/www/sounds/SIREN.WAV"; // doesnt work
//String path = "/data/data/com.myproject.d08062014f/files/www/sounds/SIREN.WAV"; // doesnt work
// all above does not work
Log.d("command", "command:" + path); // to check path string
String path = "file:///mnt/sdcard/media/audio/notifications/facebook_ringtone_pop.m4a"; // This one works!
MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(path);
} 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 {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.start();
}
Update on 09-10-2014
stackoverflow.com/a/4955915/856007 – Abdullah Shoaib Aug 12 at 7:49
thank you for the reference link below, I was able to get it working with
File file = new File(path); // acquire the file from path string
FileInputStream inputStream = new FileInputStream(file);
mMediaPlayer.setDataSource(inputStream.getFD());
inputStream.close();

Unable to set string to object

got my code working. Just having a little trouble with one part.
public void picksound(){
Intent mIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(mIntent, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent mIntent) {
if (resultCode == RESULT_OK && null != mIntent) {
if (requestCode == 1) {
Uri selectedRing = mIntent.getData();
}
}}
private void playSong(String selectedRing){
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(selectedRing);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
public void alarmmsg(){
//ringtone player
playSong(selectedRing);
//
So that's the code I am working with. When I try to call the playSong function, I am asked for a string, and the only string it seems to accept is "null". Can someone help to see what I've done wrong?
Try changing this line :
MediaPlayer mp = new MediaPlayer();
To this:
MediaPlayer player = MediaPlayer.create(this, Uri.parse("http://www.urltofile.com/file.mp3"));

Categories