public class gameHomeScreen extends Activity implements View.OnClickListener{
public static Socket socket;
private Button button;
private PrintWriter printwriter;
private BufferedReader bufferedReader;
String serverReply = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_game_home_screen);
if(login.client!=null){
socket = login.client;
}else if(signup.client!=null){
socket = signup.client;
}
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
public void onBackPressed() {
moveTaskToBack(true);
}
#Override
public void onClick(View v) {
button.setText("Waiting...");
SendMessage sm = new SendMessage();
sm.execute();
while(!serverReply.equals("game_found")) {
//do nothing
}
Intent i = new Intent(this, InGame.class);
startActivity(i);
finish();
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
printwriter = new PrintWriter(socket.getOutputStream(), true);
printwriter.println("game_queue"); // write the message to output stream
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
do {
serverReply = bufferedReader.readLine();
}while(!serverReply.equals("game_found"));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
}
This line of code doesnt work :
button.setText("Waiting...");
I've tried using handlers and using the UIThread but nothing works. The text only changes for half a second to "waiting..." whenever a game is found though, its pretty strange...
You're hanging the UI thread:
while(!serverReply.equals("game_found")) {
//do nothing
}
Don't do this on the onClick method. This method is called from the UI thread and you're locking it up (which might also give you an ANR).
Remove the loop from onClick:
#Override
public void onClick(View v) {
button.setText("Waiting...");
SendMessage sm = new SendMessage();
sm.execute();
//while(!serverReply.equals("game_found")) {
// do nothing
//}
//Intent i = new Intent(this, InGame.class);
//startActivity(i);
//finish();
}
And start the intent in your AsyncTask:
private class SendMessage extends AsyncTask<Void, Void, Void> {
// ...
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent i = new Intent(this, InGame.class);
startActivity(i);
finish();
}
}
Related
I am building an app that will check data from a URL in json and display it in the UI. I have created a service that I want to run the Async task. The service works fine and runs fine, I just can't get the task to run. Any ideas?
public class Getmonitors extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> monitorList;
ProgressDialog pDialog;
#Override
public void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(myActivity.this);
pDialog.setMessage("Please wait...");
Log.v(LOG_TAG, "PLEASE WAIT");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
NewWebRequest webreq = new NewWebRequest();
// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, NewWebRequest.GET);
monitorList = ParseJSON(jsonStr);
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
// Intent intent = new Intent(MainActivity.this, myService.class);
// startService(intent);
ListAdapter adapter = new SimpleAdapter(
myActivity.this, monitorList,
R.layout.list_item, new String[]{TAG_NAME, TAG_EMAIL,
TAG_STATUS}, new int[]{R.id.name,
R.id.email, R.id.statuslist});
setListAdapter(adapter);
// setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) findViewById(R.id.imageview1);
iv.setVisibility(View.VISIBLE);
new Getmonitors().execute();
iv.setVisibility(View.INVISIBLE);
}
});
//service onDestroy callback method will be called
findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(myActivity.this, myService.class);
startService(intent);
}
});
//service onDestroy callback method will be called
findViewById(R.id.stop_Service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(myActivity.this, myService.class);
stopService(intent);
}
});
}
}
And in the Service:
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
#Override
public void run() {
//Your logic that service will perform will be placed here
//In this example we are just looping and waits for 1000 milliseconds in each loop.
for (int i = 0; i < 2; i++) {
try {
Thread.sleep(20000);
} catch (Exception e) {
}
if(isRunning) {
Log.v("WORKS!!!!!!!!!!!!!!", " url");
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
This runs my Async task in another task every 30 seconds, ten times.
Main Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
new Getmonitors().execute();
}
ProgressBar progressBar;
private MyBroadcastReceiver myBroadcastReceiver;
private MyBroadcastReceiver_Update myBroadcastReceiver_Update;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar)findViewById(R.id.progressbar);
//prepare MyParcelable passing to intentMyIntentService
String msgToIntentService = "Android-er";
//Start MyIntentService
final Intent intentMyIntentService = new Intent(this, MyIntentService.class);
intentMyIntentService.putExtra(MyIntentService.EXTRA_KEY_IN, msgToIntentService);
startService(intentMyIntentService);
myBroadcastReceiver = new MyBroadcastReceiver();
myBroadcastReceiver_Update = new MyBroadcastReceiver_Update();
//register BroadcastReceiver
IntentFilter intentFilter = new IntentFilter(MyIntentService.ACTION_MyIntentService);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(myBroadcastReceiver, intentFilter);
IntentFilter intentFilter_update = new IntentFilter(MyIntentService.ACTION_MyUpdate);
intentFilter_update.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(myBroadcastReceiver_Update, intentFilter_update);
}
#Override
protected void onDestroy() {
super.onDestroy();
//un-register BroadcastReceiver
unregisterReceiver(myBroadcastReceiver);
unregisterReceiver(myBroadcastReceiver_Update);
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
**new Getmonitors().execute();**
//this is the async task
int update = intent.getIntExtra(MyIntentService.EXTRA_KEY_UPDATE, 0);
progressBar.setProgress(update);
//un-register BroadcastReceiver
unregisterReceiver(myBroadcastReceiver);
unregisterReceiver(myBroadcastReceiver_Update);
myBroadcastReceiver = new MyBroadcastReceiver();
myBroadcastReceiver_Update = new MyBroadcastReceiver_Update();
//register BroadcastReceiver
IntentFilter intentFilter = new IntentFilter(MyIntentService.ACTION_MyIntentService);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(myBroadcastReceiver, intentFilter);
IntentFilter intentFilter_update = new IntentFilter(MyIntentService.ACTION_MyUpdate);
intentFilter_update.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(myBroadcastReceiver_Update, intentFilter_update);
}
}
public class MyBroadcastReceiver_Update extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int update = intent.getIntExtra(MyIntentService.EXTRA_KEY_UPDATE, 0);
progressBar.setProgress(update);
}
}
MyIntentService
public static final String ACTION_MyIntentService = "com.example.androidintentservice.RESPONSE";
public static final String ACTION_MyUpdate = "com.example.androidintentservice.UPDATE";
public static final String EXTRA_KEY_IN = "EXTRA_IN";
public static final String EXTRA_KEY_OUT = "EXTRA_OUT";
public static final String EXTRA_KEY_UPDATE = "EXTRA_UPDATE";
String msgFromActivity;
String extraOut;
public MyIntentService() {
super("com");
}
#Override
protected void onHandleIntent(Intent intent) {
//get input
msgFromActivity = intent.getStringExtra(EXTRA_KEY_IN);
extraOut = "Hello: " + msgFromActivity;
for (int x = 0; x <= 10; x++) {
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.v("loop", "");
e.printStackTrace();
Intent intentUpdate = new Intent();
intentUpdate.setAction(ACTION_MyUpdate);
intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
intentUpdate.putExtra(EXTRA_KEY_UPDATE, i);
sendBroadcast(intentUpdate);
}
//send update
Intent intentUpdate = new Intent();
intentUpdate.setAction(ACTION_MyUpdate);
intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
intentUpdate.putExtra(EXTRA_KEY_UPDATE, i);
sendBroadcast(intentUpdate);
}
//return result
Intent intentResponse = new Intent();
intentResponse.setAction(ACTION_MyIntentService);
intentResponse.addCategory(Intent.CATEGORY_DEFAULT);
intentResponse.putExtra(EXTRA_KEY_OUT, extraOut);
sendBroadcast(intentResponse);
}
}
I had to establish a socket in ActivityA in normal and ready to send data,
but now I want to also be able to use the same socket connection to transmit the data in ActivityB.I have looked for information on the Internet, it seems can use the singleton.I studied for a few days, I still don't know how to start, even find some examples of exercises too, but still do not know how to use my original program.
I want to first establish between ActivityA and SERVER connection, and to pass a value to the SERVER, then press the button to switch to ActivityB, and also transmit values to SERVER
Give me some advice or teaching sites can be, so that I can continue to study it, thank you very much
Establish socket methods:
public class MainActivity extends Activity {
Button Btn_Wifi,Btn_Power,Btn_Flame;
Boolean connected=false;
Boolean powerstatus=false;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null ;
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView();
setListensers();
setButtonStatus();
}
private void mainView(){
Btn_Wifi = (Button) findViewById(R.id.Btn_Wifi);
Btn_Power = (Button) findViewById(R.id.Btn_Power);
Btn_Flame = (Button) findViewById(R.id.Btn_Flame);
}
private void setListensers(){
Btn_Wifi.setOnClickListener(BtnWifiOnClickListener);
Btn_Power.setOnClickListener(BtnPowerOnClickListener);
Btn_Flame.setOnClickListener(BtnFlameOnClickListener);
}
private void setButtonStatus(){
Btn_Power.setEnabled(false);
Btn_Flame.setEnabled(false);
}
Button.OnClickListener BtnWifiOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!connected){
try {
socket = new Socket("IP", PORT);
dataOutputStream = new DataOutputStream(socket.getOutputStream());//and stream
changeConnectionStatus(true);//change the connection status
}catch (UnknownHostException e) {
changeConnectionStatus(false);
}catch (IOException e) {
changeConnectionStatus(false);
}
}else{
try {//try to close the socket
socket.close();
changeConnectionStatus(false);//change the connection status
} catch (UnknownHostException e) {//catch and
changeConnectionStatus(false);
} catch (IOException e) {//catch and
changeConnectionStatus(false);
}
}
}
};
Button.OnClickListener BtnPowerOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!powerstatus){
try {
byte[] pon ={(byte) 0x10,(byte) 0x10};
dataOutputStream.write(pon);
dataOutputStream.flush();
PowerStatus(true);
}catch(Exception obj){
PowerStatus(false);
}
}else{
try {
byte[] poff ={(byte) 0x11,(byte) 0x11};
dataOutputStream.write(poff); //writeBytes(String str)
dataOutputStream.flush();
PowerStatus(false);
}catch(Exception obj){
PowerStatus(true);
}
PowerStatus(false);
}
}
};
Button.OnClickListener BtnFlameOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, FlameActivity.class);
startActivity(intent);
}
};
public void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
if(isConnected){//if connection established
Btn_Wifi.setText("CONNECTED");
Btn_Power.setEnabled(true);
}else{
Btn_Wifi.setText("NOT WIFI");
Btn_Power.setText("POWER OFF");
Btn_Power.setEnabled(false);
PowerStatus(false);
}
}
public void PowerStatus(Boolean isPowerOn) {
powerstatus=isPowerOn;//change variable
if(isPowerOn){//if connection established
Btn_Power.setText("POWER ON");
Btn_Flame.setText("SET FLAME");
Btn_Flame.setEnabled(true);
}else{
Btn_Power.setText("POWER OFF");
Btn_Flame.setText("CANT SET FLAME");
Btn_Flame.setEnabled(false);
}
}
}
You can certainly use it by declaring,i.e: in MainActivity which creates socket connection,static YourSocketClass objSocket // which creates connection and to use it in another Activity just called it as follow i.e:MainActivity.objSocket.yourMethod(any_param). by declaring static you can access it.
public static CommunicationClient objCommunicationClient;
public boolean setConnection(final String ipAddress, final Context context,
final boolean isFromSearch) {
class EstablishConnection extends AsyncTask<Void, Void, Boolean> {
ProgressDialog objDialog;
#Override
protected void onPreExecute() {
objDialog = new ProgressDialog(context);
objDialog.setMessage(context.getResources().getString(
R.string.strConnecting));
objDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
objDialog.show();
objDialog.setCancelable(false);
objDialog.setCanceledOnTouchOutside(false);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean isConnected = false;
boolean isValid = false;
StrictMode.setThreadPolicy(policy);
objCommunicationClient = new CommunicationClient(ipAddress);
isSocketInitiated = objCommunicationClient.initSocket();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
CommonUtils.SSID = info.getSSID();
if (!isSocketInitiated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.strCantConnect),
Toast.LENGTH_LONG).show();
}
});
} else {
isConnected = true;
if (!isFromSearch) {
CommonUtils.IP = ipAddress;
try {
objCommunicationClient.sendRequest(context,
"<APP_SPECIFIC>");
} catch (Exception e) {
e.printStackTrace();
}
} else {
isValid = isFromSearch;
}
if (isValid) {
final Intent objIntentToGraph = new Intent(context,
GraphDataActivity.class);
objIntentToGraph
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(objIntentToGraph);
overridePendingTransition(
R.anim.slide_in_right,
R.anim.slide_out_left);
finish();
}
});
}
}
return isConnected;
}
#Override
protected void onPostExecute(Boolean result) {
try {
objDialog.cancel();
} catch (Exception err) {
err.printStackTrace();
}
super.onPostExecute(result);
}
}
boolean status = false;
try {
status = new EstablishConnection().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return status;
}
}
// and in my other Activity i called it as
MainActivity_HomePage.objCommunicationClient.sendRequest(
context, CommonUtils.STOP_COMMAND); //send request is method which send message to server.
I'm trying the Android-Network-Intents library from pocmo -->here the link
It looks great, but I'm running into a nullpointer exception:
11-25 13:28:37.744 7618-7634/be.appwise.networkintents E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-684
Process: be.appwise.networkintents, PID: 7618
java.lang.NullPointerException
at be.appwise.networkintents.MainActivity$1.onDiscoveryStarted(MainActivity.java:88)
at com.androidzeitgeist.ani.discovery.DiscoveryThread.run(DiscoveryThread.java:66)
Internet permission is in place.
This is my code (based on their sample project)
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private static final String EXTRA_MESSAGE = "message";
Discovery discovery;
boolean discoveryStarted;
#InjectView(R.id.txtInput)
EditText txtInput;
#InjectView(R.id.txtReceived)
TextView txtReceived;
#InjectView(R.id.txtFeedback)
TextView txtFeedback;
#OnClick(R.id.btnSend)
public void send(View view) {
Intent intent = new Intent();
intent.putExtra(EXTRA_MESSAGE, "Testing Network intents");
Transmitter transmitter = new Transmitter();
try {
transmitter.transmit(intent);
} catch (TransmitterException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
discovery = new Discovery();
discovery.setDisoveryListener(discoveryListener);
}
#Override
protected void onResume() {
super.onResume();
//Enable discovery
try {
discovery.enable();
discoveryStarted = true;
} catch (DiscoveryException e) {
discoveryStarted = false;
e.printStackTrace();
txtFeedback.setText("error discovery " + e.getMessage());
}
}
#Override
protected void onPause() {
super.onPause();
//Disable discovery
if (discoveryStarted) {
discovery.disable();
}
}
DiscoveryListener discoveryListener = new DiscoveryListener() {
#Override
public void onDiscoveryStarted() {
txtFeedback.setText("onDiscoveryStarted ");
}
#Override
public void onDiscoveryStopped() {
txtFeedback.setText("onDiscoveryStopped ");
}
#Override
public void onDiscoveryError(Exception e) {
txtFeedback.setText("onDiscoveryError ");
}
#Override
public void onIntentDiscovered(InetAddress inetAddress, Intent intent) {
if (intent.hasExtra(EXTRA_MESSAGE)) {
txtFeedback.setText("onIntentDiscovered ");
String message = intent.getStringExtra(EXTRA_MESSAGE) + " from " + inetAddress;
txtReceived.setText(message);
} else {
txtFeedback.setText("Intent discovered, no message");
}
}
};
}
Your txtFeedback is null. Set it with findViewById on your onCreate after you call setContentView. You might want to check the xml again to check if you're using the right id on: #InjectView(R.id.txtFeedback)
I'm developing DES decryption in Android platform.
this is my main
package com.example.crack;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class Main extends Activity {
public final static String EXTRA_MESSAGE = "com.example.crack.MESSAGE";
public final static String EXTRA_PLAINTEXT = "com.example.crack.PLAINTEXT";
public final static int ENCRYPTION_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendMessage(View view) {
Intent intent = new Intent(this, encryption.class);
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == ENCRYPTION_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
String result = data.getStringExtra(encryption.EXTRA_ENCRYPTION_RETURN);
Intent intent = new Intent(this, DisplayMessage.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
}
}
}
and this is the partial of my encrpytion
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.encryption);
Intent intent = getIntent();
message = intent.getStringExtra(Main.EXTRA_MESSAGE);
//Dictionary
is = getResources().openRawResource(R.raw.english);
in = new BufferedReader(new InputStreamReader(is));
readDic();
String result = "";
try {
result = decryptBruteForce();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent returnIntent = new Intent();
returnIntent.putExtra(EXTRA_ENCRYPTION_RETURN,result);
setResult(RESULT_OK,returnIntent);
finish();
}
when i click on the button, it calls the sendMessage function, while it is running the decryption the screen just black out until it finish running.
I had try using progress bar follow this guide, but not working, I need a button that can stop the process while running.
And is it possible to set a log on view, which show what the function is doing right now? like what is shown in the IDE log? Example, showing what key is the decryption trying right now.
Or maybe just a progress bar or please wait will do too.
I tried to change the sendMessage to this, yet it still black out and crash
public void sendMessage(View view) {
final Intent intent = new Intent(this, encryption.class);
view.setEnabled(false);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
b.setEnabled(true);
}
}
};
task.execute((Void[])null);
}
if I put sleep to 50000, it did not crash, but still it black out.
You can do it with a Thread and a Handler. While you try each combination, you update the progress bar.
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle savedInstanceState)
{
.... // Other initializations
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mProgress.setMax(dictionaryLength);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
for (int i=0 ; i<dictionaryLength ; i++)
{
mProgressStatus = decryptBruteForce(i);
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
}
However i recommend you to use AsyncTask to do background operations while you need to update the UI to show the progress or info about whats going on.
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html
Its a good habit to add a cancel control in your loop, so you can finish it from outside of the AsyncTask (for example another button in you UI).
private class DecryptTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... words)
{
long wordsDecrypted = 0;
for (int i = 0; i < words.length ; i++) {
wordsDecrypted += decryptBruteForce(i);
publishProgress(i);
// Escape early if cancel() is called
if (isCancelled())
break;
}
return wordsDecrypted;
}
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Decrypted " + result + " words");
}
}
And you can cancel the AsyncTask from outside with the cancel method:
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html#cancel(boolean)
PD: Codes are not tested, just examples to show how it works
i've an progress circle that is set inside an AsyncTask. It shows for about a second as the asynctask is executing, then disappears. once the task is completed if i press the back button the circle shows for a long time. why is this?
private class AsyncGetRota extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(NfcscannerActivity.this,
"Connecting to Server"," retrieving rota...", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
[update]
getRota.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "onclicked getRota");
String[] params = new String[]{"36", "18-09-2012"};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
for(int i = 0; i < 60; i++){
if(agr.isCancelled() == true){
Log.e(TAG, "asyncTask is finished");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of for loop
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}// end of onclick
});
...
new MyAsyncTask().execute(string);
...
}
class MyAsyncTask extends AsyncTask<String, Void, Whatever > {
...
#Override
protected Whatever doInBackground(String... params) {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
return rotaArray;
}
#Override
protected void onPostExecute(Whatever result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
Intent intent = new Intent(NfcscannerActivity.this, GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", result);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}
}
You should let the execution continue after you start the AsyncTask, and not block it using some loop or something..
try to implement it like this:
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Processing...");
dialog.show();
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
};
that's always works for me
Couple of problems here, you do not initialize ProgressDialog, initialize a constructor that initializes you ProgressDialog like this...
public AsyncGetRota(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
Then in onPostExecute check if your ProgressDialog is null, like this
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
}