Is portrait/landscape transition effect to AsyncTask - android

I have developed a application connect with wi-fi. In that app portrait/landscape transition restart the activity when rotate the phone and interrupt the socket connection. Then I add portrait to AndroidManifest.xml file then problem have been solved. I want to know that is portrait/landscape transition effect to Async-Task also?
<activity
android:name="login"
android:label="#string/login_title"
android:configChanges="orientation|screenSize" >
</activity>
Login.java file
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class login extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
try{
Button buttonSignin = (Button) this.findViewById(R.id.btnSignIn);
//This is the place gives nullpointerException
buttonSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText user=(EditText) findViewById(R.id.txtUserName);
EditText pass=(EditText) findViewById(R.id.txtPassword);
if(user.getText().toString()== "")
{
return;
}
else if(pass.getText().toString()== "")
{
return;
}
else
{
LoginRequest reqs_login = new LoginRequest(login.this,login.this);
reqs_login.where="Login_Data";
reqs_login.title="Login";
reqs_login.username=user.getText().toString();
reqs_login.password=pass.getText().toString();
reqs_login.execute();
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:1 on uplod file", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:2 File may be already exists", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}

Use this in your AndroidManifest.xml activity,
android:configChanges="orientation|screenSize"
working for me in AsyncTask also

I guess the Answer would be NO because the Async task (Background task) once started executing inBackground it will not stop until complete execution of that code in background. No matter App is in whichever State , Even the App is minimized it does not affect the Async Task. So Changing Landscape / Portrait mode will not affect the AsyncTAsk (InBackground) method. hope this will help...

What is the best way to retain active objects—such as running Threads, Sockets, and AsyncTasks—across device configuration changes?
Deprecated: Override onRetainNonConfigurationInstance()
transferring an active object across Activity instances was merely a matter of returning the active object in onRetainNonConfigurationInstance() and retrieving it in getLastNonConfigurationInstance(). As of API 13, these methods have been deprecated in favor of the more Fragment's setRetainInstance(true/false)
Recommended: Manage the Object Inside a Retained Fragment
Fragment#setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle
For more details please go through the below
Handling Configuration Changes
Hope this will help you.

Related

Android App Keep On Crashing In API_Lev 23 [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 1 year ago.
I am new to android dev
I have made as simple app in android (for api_version greater than 23) which fetches the name of all running apps. But the app doesn't work properly. When I click the button the functionality registered in "onClickListner" is not working.
package com.sakthi.appban;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayAllApps();
}
});
}
private void displayAllApps(){
PackageManager pm = getPackageManager();
List<ApplicationInfo> installedApplications = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for(ApplicationInfo application : installedApplications){
Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "Task Ended", Toast.LENGTH_SHORT).show();
}
Hope I will get help
Thanks in advance
I think you might have seen these message in logs if you run this code you will get this error when you click on the button
Error:
java.lang.IllegalStateException: You must either set a text or a view
Here application.name may get null for some of the apps. This may cause IllegalStateException because you are passing null to a Toast.
To fix this simply add an if condition to null check like this:
if(application.name != null) {
Toast.makeText(this, application.name, Toast.LENGTH_SHORT).show();
}
Then it should work.
Update:
You can remove this code from your code which causing ANR:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
The problem is that I am trying to loop in the UI thread.
So the UI thread cannot handle the UI operation..
and my program crashed.More info here

Speech to text in emulator: No Activity found to handle Intent

I want to ask how I can use speech to text code on my emulator. My codes work on real device but not work on emulator. The error said :
No Activity found to handle Intent { act=android.speech.action.RECOGNIZE_SPEECH (has extras) }
What can I do?
package net.viralpatel.android.speechtotextdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
}
You need to install onto your emulator an app that contains an Activity that handles the RECOGNIZE_SPEECH-intent. You might be able to find Google's VoiceSearch.apk on the web.
There are certain things you can't test using an emulator. Speech to text is on of them.
I'm not sure about this, but you can't use this android feature with the emulator.
No matter what, you should handle this exception with a try/ catch an give some feedback to the user.
You can check if there is that Activity in current device running your app doing something like:
PackageManager pm = context.getPackageManager();
List<ResolveInfo> infoList = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (infoList.size() == 0) {
/** Show some feedback to user if there is the activity. Something like "Your device is not abl to run this feature..."*/
}else{
/**Your current code goes here.*/
}
Let me know if it helps.
You need to install com.google.android.voicesearch application on target device which has no voice recognition activity like:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.voicesearch"));
startActivity(browserIntent);
if you try to install Google's Search app - it won't help since it doesn't contain the VR engine inside and thus it will try to do the same - install com.google.android.voicesearch app but it could fail due to a bug in package name (pname:com.google.android.voicesearch instead of just pure package name). However com.google.android.voicesearch installation might be impossible due to "Not available in your country".
You might need a virtual SD Card. You can refer here

Can not use MediaRecorder on Android Emulator. Is the storage location wrong?

I'm trying to record sound using Android Emulator. I know that this question is popular over the internet, I checked many posts, it seems that only one person succeded: Can the Android emulator record and play back audio using pc hardware?. (it think he used
File fTmFile; insteadof String fTmpFile;
which i also tried). And following Philip's advice and the official site tutorial http://developer.android.com/guide/topics/media/audio-capture.html and also other resources, I'm still not able to record. My application throws exception at line:
fMediaRecorder.prepare();
more exactley, this is what I first get:
W/System.err(1042): java.io.FileNotFoundException: /mnt/sdcard/audiorecordtest.3gp (Permission denied)
which makes me think is something wrong with the storage location, because even I added 'SD Card Support' property for the emulator with size 256 MiB, I'm not able to acces it, furthermore I can see in the emulator the message: "Your phone does not have a SD Card inserted" when I go to Music.
I added both audio record and external storage permissions, in AndroidManifest.xml and both audio (record+playback) hardware settings to the emulator 2.3.3 on Win 7. Is anything wrong within my app, the way I storage the file or something else? Please, if anybody has any idea feel free to share, it will be appreciated.
Here is the full source code:
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class RecordSoundActivity extends Activity {
private MediaRecorder fMediaRecorder = null;
private Button btnrecord;
private Button btnstop;
String fTmpFile;
public RecordSoundActivity() {
fTmpFile = Environment.getExternalStorageDirectory().getPath();
fTmpFile += "/audiorecordtest.3gp";
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnrecord = (Button) findViewById(R.id.button1);
btnstop = (Button) findViewById(R.id.button2);
btnrecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(RecordSoundActivity.this, "Recording...", Toast.LENGTH_LONG).show();
Recording();
}
});
btnstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fMediaRecorder.stop();
fMediaRecorder.release();
}
});
}
public void Recording() {
fMediaRecorder = new MediaRecorder();
fMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
fMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
fMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
fMediaRecorder.setAudioChannels(1);
fMediaRecorder.setAudioSamplingRate(8000);
fMediaRecorder.setOutputFile(fTmpFile);
try {
fMediaRecorder.prepare();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
fMediaRecorder.start();
} catch (IllegalStateException e) {
// TODO: handle exception
e.printStackTrace();
}
//fMediaRecorder.stop();
//fMediaRecorder.release();
}
}
Try and see if it works for Android 4.0. I know I had some issues with the camera in the emulator, in lower version (Lower than 4.0) it just wouldn't recognize my laptop webcam. But when I tried it on 4.0, when the AVD was loading a popup message came and asked me if I want to connect the webcam to the AVD, and once I agreed it worked.
Another poster in SO asked this question too, about the camera, and changing the AVD version to 4.0 did help him.
Maybe its the same for audio recording too, as both are external hardware for the typical PC.

How can you set the http proxy programmatically?

I'm looking for a programmatic way to set-up http proxy settings for android handsets. I've tried using android.provider.Settings.System.putString() to set System.HTTP_PROXY, but my call fails (I'm using a 2.2 emulator image at the moment). My code looks like:
if (System.putString(getContentResolver(), System.HTTP_PROXY, "10.10.2.1:8080")) {
tv.append("put for HTTP_PROXY succeeded.\n");
}
else {
tv.append("put for HTTP_PROXY failed.\n");
}
I've also added to my android manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
..although it's not clear from the docs which permission, if any, is required.
I'm familiar with this SO thread, but the technique there requires manual adb commands, which require the SDK tools and (possibly) a rooted phone.
Is there a way to accomplish this? Ideally, I'd like away to set an http proxy that will be used for both data and wifi connections.
It's not possible to do this as a 3rd-party app. You get this message:
12-07 12:39:37.736: W/PackageManager(85): Not granting permission android.permission.WRITE_SECURE_SETTINGS to package com.mgranja.xxxxxxx (protectionLevel=3 flags=0xbe46)
Only apps that are signed with the same key as system apps can get this permission (i.e.: if you cook your own rom, you could add that funcionality)
More info about permission levels on this question, specially adamk's answer.
Why are these permissions being refused?
If you are limiting the use of proxies to your own application you can use the Proxy and ProxySelector API.
To set the proxy check Mike's answer;
Following is code snippet to retrieve proxy details
public static String getProxyDetails(Context context) {
String proxyAddress = new String();
try {
if (IsPreIcs()) {
proxyAddress = android.net.Proxy.getHost(context);
if (proxyAddress == null || proxyAddress.equals("")) {
return proxyAddress;
}
proxyAddress += ":" + android.net.Proxy.getPort(context);
} else {
proxyAddress = System.getProperty("http.proxyHost");
proxyAddress += ":" + System.getProperty("http.proxyPort");
}
} catch (Exception ex) {
//ignore
}
return proxyAddress;
}
It'll return empty if some exception or no proxy detected;
You can set the proxy for your application VM, but due to security reasons, third party apps may not have the functionality to set device proxy.
I found something here that looks like it might work
package com.BrowserSettings;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.provider.Settings;
public class BrowserSettingsUI extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.Button01);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
Settings.System.putString(getContentResolver(),
Settings.System.HTTP_PROXY, "127.0.0.1:100");//enable proxy
}catch (Exception ex){
}
}
});
final Button button2 = (Button) findViewById(R.id.Button02);
button2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
Settings.System.putString(getContentResolver(),
Settings.System.HTTP_PROXY, "");//disable proxy
}catch (Exception ex){
}
}
});
}
}
You must add
<uses-permission android:name=”android.permission.WRITE_SETTINGS” />
to your manifest.
Did you try to call the com.android.settings.ProxySelector activity and let the user to enter the proxy? It's stored globally, but seems that it doesn't support the standard Proxy and ProxySelector API (for this problem there is already another question: How users/developers can set the Android's proxy configuration for versions 2.x?)

a basic Text to speech app not working

i tried the following on the emulator but the as the app starts it gives a runtime error . could someone please help me on this . Heres' the code i tried
package com.example.TextSpeaker;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
public class TextSpeaker extends Activity {
/** Called when the activity is first created. */
int MY_DATA_CHECK_CODE = 0;
private TextToSpeech mtts;
String test1="hello world";
String test2="hi i am working fine";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myintent = new Intent();
myintent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(myintent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestcode,int resultcode,Intent data)
{
if(requestcode == MY_DATA_CHECK_CODE)
{
if(resultcode==TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
// success so create the TTS engine
mtts = new TextToSpeech(this,(OnInitListener) this);
mtts.setLanguage(Locale.ENGLISH);
mtts.speak(test1, TextToSpeech.QUEUE_FLUSH, null);
mtts.speak(test2, TextToSpeech.QUEUE_FLUSH, null);
}
else
{
//install the Engine
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(install);
}
}
}
}
I've stumbled upon this question well over a year after it was posted, but I'm going to go ahead and answer anyway, in the sheer hope it'll help anyone else who ends up here in the future.
I'm writing this against 2.1, so apologies if you were working with <2.1 (no tags on question)
There are a few things I can spot immediately that may give you a little grief.
Firstly, the following :
mtts.speak(test1, TextToSpeech.QUEUE_FLUSH, null);
mtts.speak(test2, TextToSpeech.QUEUE_FLUSH, null);
If I understand the TextToSpeech API correctly, using QUEUE_FLUSH will flush out anything thats currently being spoken, so its possible that the second line is executing before the first has actually spoken, and you'd experience what you've stated above, that only the last one is being spoken.
Ideally, you only want one of those lines there, if the user puts in a different String, then just pass that through and let it flush out.
Next, you should invest in an onDestroy override, in here you can shutdown the mtts object, this prevents your app from hogging usage to the TTS engine, its always nice to free up resources when you're done with them, you wouldn't leave a ResultSet open now would you?!
#Override
public void onDestroy
() {
// Don't forget to shutdown!
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
Also, as you state, it'll only speak English, because of the line you're using :
mtts.setLanguage(Locale.ENGLISH);
That's easy to correct, just set a different locale. Perhaps have some buttons and set the locale accordingly. I believe that the Google TTS engine currently only supports English, French, German, Italian and Spanish, but 3rd party TTS engines may offer more.
If all else fails, I wrote a tutorial here that might be of use.
Good luck!

Categories

Resources