How to end AsyncTask onBackPress() - android

how to stop asynctask on android backpress i want to stop this activity so that when it goes back to previous activity this activity is completely closed
this activity does its work in background , as it is supposed to do, my problem is when we click the android back button this activity should completely stop and go back to first activity i did somne search and came to know the asynctask should be stopped on back press
i tried that but ii doesnot seem to work how can this be done in the below code
package com.Blog.blogname;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import com.Blog.blogname.parser.DOMParser;
import com.Blog.blogname.parser.RSSFeed;
public class SplashActivity extends Activity {
//String RSSFEEDURL = "http://feeds.blogname.com/blogname?format=xml";
//String RSSFEEDURL = "http://blogname.blogname.com/feeds/posts/default?alt=rss";
//int position = i.getExtras().getInt("position");
//String[] country = i.getStringArrayExtra("country");
//Toast.makeText(this, i.getStringArrayExtra("country") + "was selected" , Toast.LENGTH_LONG).show();
//String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
//String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/country[position]?alt=rss";
RSSFeed feed;
String fileName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
// //public String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity!",
Toast.LENGTH_LONG);
toast.show();
//feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//feed = myParser.parseXml(RSSFEEDURL);
//feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss");
feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
// private RSSFeed ReadFeed(String fName) {
//
// FileInputStream fIn = null;
// ObjectInputStream isr = null;
//
// RSSFeed _feed = null;
// File feedFile = getBaseContext().getFileStreamPath(fileName);
// if (!feedFile.exists())
// return null;
//
// try {
// fIn = openFileInput(fName);
// isr = new ObjectInputStream(fIn);
//
// _feed = (RSSFeed) isr.readObject();
// }
//
// catch (Exception e) {
// e.printStackTrace();
// }
//
// finally {
// try {
// fIn.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// return _feed;
//
// }
// #Override
// public void onBackPressed()
// {
// finish();
// }
// #Override
// public void onBackPressed(){
// if(condition){
// super.onBackPressed(); //Normal behaviour
// } else {
// startLisActivity(feed);
// }
// }
//private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
//private long mBackPressed;
//#Override
// public void onBackPressed()
// {
// if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
// {
// super.onBackPressed();
// return;
// }
// else if(mBackPressed + TIME_INTERVAL < System.currentTimeMillis()){ Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
// else {
// //startLisActivity(feed);
// #Override
// protected void onPostExecute(Void result) {
// super.onPostExecute(result);
//
// startLisActivity(feed);
// }
//}
// mBackPressed = System.currentTimeMillis();
//}
#Override
// public void onBackPressed() {
// //DOMParser().cancel(true);
// AsyncLoadXMLFeed.cancel(true);
// // If you want to finish the activity you can use below code
// finish();
// }
// public void onBackPressed()
// {
//
// .cancel(true);
// }
//public void onBackPressed(){
//
//
// if (AsyncLoadXMLFeed != null) if (AsyncLoadXMLFeed.getStatus() == Status.RUNNING) AsyncLoadXMLFeed.cancel(true);
// finish();
// //overridePendingTransition(R.anim.zoom_enter,R.anim.zoom_exit);
// }
}

Simply call cancel in activities onDestroy()
public SplashActivity extends Activity {
private AsyncLoadXMLFeed loader;
#Override
public void onCreate(Bundle b){
super.onCreate(b);
...
// Connected - Start parsing
loader = new AsyncLoadXMLFeed();
loader.execute();
}
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
loader.cancel(true);
}
}
The official android documentation says:
A task can be cancelled at any time by invoking cancel(boolean).
Invoking this method will cause subsequent calls to isCancelled() to
return true. After invoking this method, onCancelled(Object), instead
of onPostExecute(Object) will be invoked after
doInBackground(Object[]) returns. To ensure that a task is cancelled
as quickly as possible, you should always check the return value of
isCancelled() periodically from doInBackground(Object[]), if possible
(inside a loop for instance.)

You need to keep a reference to your running AsyncTask object and when back is pressed (or the Activity is paused) you need to call the cancel() method of the instance object. Your commented out code is trying to call it as a static method, which it is not.

The ProgressDialog has a convenient method that gets called when the user press back.
taskParseKmlDownload = new TaskParseKmlDownload(kmlSummary,
new WeakReference<Context>(this),
this, mMap);
taskParseKmlDownload.execute();
taskParseKmlDownloadProgress = new ProgressDialog(this);
taskParseKmlDownloadProgress.setMessage("Parsing KML File");
taskParseKmlDownloadProgress.show();
taskParseKmlDownloadProgress
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
taskParseKmlDownload.cancel(false);
}
});
Then in the task you have to check .isCanceled()
Below I'm simply returning -1 if the user cancels the task.
// check for cancel before next download
if (isCancelled()) {
return RESULT_ABORTED;
}

Related

Android bluetooth printer app works fine in debug mode but doesn't work in release mode

I am writing an Android app to print text on a bluetooth thermal printer.
Here is the complete code
The app works fine in the debug mode but when I generate a signed APK and install it on the device, it does not respond at all.
I have tried different solution suggested on stackoverflow but non of them worked.
This is my main activity
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.lvrenyang.io.IOCallBack;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
private Handler mHandler; // Our main handler that will receive callback notifications
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private static String TAG = "MAIN_ACTIVITY";
private Activity activity;
private Button btnConnect;
private String name = "MTP-II";
private String mac_address = "02:15:44:31:49:05";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get the activity
this.activity = this;
//Button from the XML view
btnConnect = findViewById(R.id.btnConnect);
//Start the Init Work Service Async task
new InitWorkService().execute();
//Set onClickListener for test print button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
//Check if name and address are set
if (name != "null" && mac_address != "null" && mac_address.contains(":")) {
if (!WorkService.workThread.isConnected()) {
WorkService.workThread.connectBt(mac_address);
//Sleep for 3 seconds
try {
Thread.sleep(3000);
} catch (Exception e) {
}
}
//Check if connected
if (WorkService.workThread.isConnected()) {
//Collect data in background Thread
new PrintData().execute();
} else {
Toast.makeText(activity, Global.toast_notconnect, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(activity, "Please setup printer first!", Toast.LENGTH_LONG).show();
}
}
catch(Exception e){
Log.e(TAG, e.getMessage(), e.fillInStackTrace());}
}
});
}
/**
* Background Async Task
* */
private class InitWorkService extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args){
try{
WorkService.cb = new IOCallBack() {
public void OnOpen() {
if (null != mHandler) {
Message msg = mHandler.obtainMessage(Global.MSG_IO_ONOPEN);
mHandler.sendMessage(msg);
}
}
public void OnClose() {
if (null != mHandler) {
Message msg = mHandler.obtainMessage(Global.MSG_IO_ONCLOSE);
mHandler.sendMessage(msg);
}
}
};
}
catch(Exception e){
Log.e(TAG, e.getMessage(), e.fillInStackTrace());
}
return null;
}
protected void onPostExecute(String file_url){
try {
mHandler = new MHandler(MainActivity.this);
WorkService.addHandler(mHandler);
if (null == WorkService.workThread) {
Intent intent = new Intent(activity, WorkService.class);
startService(intent);
}
}
catch (Exception e) {
Log.e(TAG, e.getMessage(), e.fillInStackTrace());
Toast.makeText(activity, "Unable to initiate the WorkService!", Toast.LENGTH_LONG).show();
}
}
}
/**
* Background Async Task
* */
class PrintData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args){
try{
int nTextAlign=1;
String text = "Test message!\r\n\r\n\r\n";
String encoding = "UTF-8";
byte[] hdrBytes = {0x1c, 0x26, 0x1b, 0x39, 0x01};
Bundle dataAlign = new Bundle();
Bundle dataTextOut = new Bundle();
Bundle dataHdr = new Bundle();
dataHdr.putByteArray(Global.BYTESPARA1, hdrBytes);
dataHdr.putInt(Global.INTPARA1, 0);
dataHdr.putInt(Global.INTPARA2, hdrBytes.length);
dataAlign.putInt(Global.INTPARA1, nTextAlign);
dataTextOut.putString(Global.STRPARA1, text);
dataTextOut.putString(Global.STRPARA2, encoding);
WorkService.workThread.handleCmd(Global.CMD_POS_WRITE,dataHdr);
WorkService.workThread.handleCmd(Global.CMD_POS_SALIGN,dataAlign);
WorkService.workThread.handleCmd(Global.CMD_POS_STEXTOUT,dataTextOut);
}catch(Exception e){
Log.e(TAG, e.getMessage(), e.fillInStackTrace());
}
return null;
}
protected void onPostExecute(String file_url){}
}
#Override
protected void onUserLeaveHint()
{
Log.d("onUserLeaveHint","Home button pressed");
super.onUserLeaveHint();
//Unregister bluetooth receiver
try{unregisterReceiver(bluetoothReceiver);}catch(Exception e){}
//Disconnect bt connection
try{WorkService.workThread.disconnectBt();}catch(Exception e){}
// remove the handler
try{WorkService.delHandler(mHandler);}catch(Exception e){}
mHandler = null;
}
/**
* Broadcast receiver for bluetooth state changes
*/
private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED))
{
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR);
switch (state)
{
case BluetoothAdapter.STATE_OFF:
// closeConnection();//Close on going connection and disable button
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
break;
case BluetoothAdapter.STATE_ON:
break;
}
}
}
};
private static class MHandler extends Handler {
WeakReference<MainActivity> mActivity;
MHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
MainActivity theActivity = mActivity.get();
switch (msg.what) {
case Global.CMD_POS_STEXTOUTRESULT:
case Global.CMD_POS_WRITERESULT: {
int result = msg.arg1;
Toast.makeText(
theActivity,
(result == 1) ? Global.toast_success
: Global.toast_fail, Toast.LENGTH_SHORT).show();
Log.v(TAG, "Result: " + result);
break;
}
}
}
}
}
Does your app manifest declare permissions for bluetooth to be used?
https://developer.android.com/guide/topics/connectivity/bluetooth#Permissions
In order to use Bluetooth features in your application, you must declare two permissions. The first of these is BLUETOOTH. You need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.
The other permission that you must declare is either
ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION. A location permission
is required because Bluetooth scans can be used to gather information
about the location of the user. This information may come from the
user's own devices, as well as Bluetooth beacons in use at locations
such as shops and transit facilities.
If it only happens when u sign the apk, it looks like u have to update ur proguard rules, to exclude the printer lib clases or similar
One reason for the application not responding is that you stop the main thread for 3 seconds on line 60 in the click listener of the button.
Replace the onCreate() method with the code below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get the activity
this.activity = this;
//Button from the XML view
btnConnect = findViewById(R.id.btnConnect);
//Start the Init Work Service Async task
new InitWorkService().execute();
final ExecutorService es = Executors.newFixedThreadPool(1);
//Set onClickListener for test print button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnConnect.setEnabled(false);
es.submit(new Runnable() {
#Override
public void run() {
connect();
}
});
}
});
}
private void connect() {
try {
//Check if name and address are set
if (name != null && mac_address != null && mac_address.contains(":")) {
if (!WorkService.workThread.isConnected()) {
WorkService.workThread.connectBt(mac_address);
//Sleep for 3 seconds
try {
Thread.sleep(3000);
} catch (Exception e) {
}
}
//Check if connected
if (WorkService.workThread.isConnected()) {
//Collect data in background Thread
new PrintData().execute();
} else {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, Global.toast_notconnect, Toast.LENGTH_SHORT).show();
}
});
}
} else {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Please setup printer first!", Toast.LENGTH_LONG).show();
}
});
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e.fillInStackTrace());
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
btnConnect.setEnabled(true);
}
});
}
Now the connection part executes in a new thread and only the UI operations go on the main one.
Please note that this code is not the optimal solution because it does not take into account the activity lifecycle. If the activity is re-created while the thread sleeps, there is still a reference kept to the old activity. But it should be a starting point for you.

Exit from application from home screen and close it

I want to close my application from splash screen automatically after showing an message if there is no internet connection available or any error occurs due to response error. My code closes the application but cant close the splash screen.Times of India(TOI) application does like this. How to implement this feature.
my splash screen activity is like this..
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 8000;
static String MENU = null;
ArrayList<String> ls = new ArrayList<String>();
private String[] categoryType;
private boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// requesting data for menu items in navigation drawer
String url = "http://guwahatinow.com/?json=get_category_index";
if (isOnline()) {
JsonObjectRequest jsonObjReqMenu = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArrayMenu= response.getJSONArray("categories");
Log.d("request", "menu");
int loop;
ls.add("Top Stories");
for (loop = 0; loop <jsonArrayMenu.length() ; loop++) {
JSONObject jsonObj = (JSONObject) jsonArrayMenu.get(loop);
String category =jsonObj.getString("title") ;
//menu.add(category);
ls.add(loop+1, category);
Log.d("menu added", category);
Log.d("element in ls", ls.get(loop));
}
ls.add("Exit");
int i = ls.size();
categoryType = new String[i];
for (int j = 0; j < i; j++) {
categoryType[j] = ls.get(j);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Please check your internet connection and try again...", Toast.LENGTH_LONG).show();
VolleyLog.d("menu error", "Error: " + error.getMessage());
flag = false;
//finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
//System.exit(0);
}
});
RequestQueue menuQueue = Volley.newRequestQueue(this);
menuQueue.add(jsonObjReqMenu);
if (flag) {
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
Log.d("main activity called", "true");
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
} else {
Toast.makeText(getApplicationContext(), "Internet connection error...", Toast.LENGTH_LONG).show();
finish();
System.exit(0);
}
/*new Handler().postDelayed(new Runnable() {
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
Log.d("main activity called", "true");
// close this activity
finish();
}
}, SPLASH_TIME_OUT);*/
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Calling the finish() method on an Activity when there is no connection available in your case or any other at where you want to close app.
In you major else block of if block for checking internet call finish() method. eg
You have you code as
if (isOnline()) {
// your Code for calling API and starting timer
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
}
Change it to
if (isOnline()) {
// your Code for calling API and starting timer
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
finish();
}
Hi please replace your code with below code where you used handler thread
CountDownTimer m_countDownTimer;
m_countDownTimer = new CountDownTimer(8000,1000) {
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
if(!isFinishing())
{
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
finish();
}
}
}.start();
Cancel CountDownTimer object in OnDestroy()
#Override
protected void onDestroy()
{
if(m_countDownTimer != null)
{
m_countDownTimer.cancel();
}
super.onDestroy();
}

android - progress black out but still running

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

DatagramSocket.receive only receives the first two Datagrams

I am sending some data to an android application over UDP. Therefore i created the following UDPReceiver-Class:
package com.example.urowatch;
import java.net.*;
import java.nio.ByteBuffer;
import java.io.*;
public class UDPReceiver extends Thread
{
private DatagramSocket m_Socket;
private int m_BufferSize;
private Boolean m_End = false;
private int m_TotalLength;
private int m_Received;
private byte[] m_Buffer;
private byte[] m_Result;
private Boolean m_IsNewResult = false;
private float m_Progress;
private int m_ImageCount = 0;
private int m_FrameErrors = 0;
public UDPReceiver(String name, int port, int bufferSize) throws IOException
{
super(name);
m_Socket = new DatagramSocket(port);
m_BufferSize = bufferSize;
m_Socket.setBroadcast(true);
m_Socket.setReceiveBufferSize(m_BufferSize);
}
public void run()
{
while(!m_End)
{
try
{
byte[] buf = new byte[m_BufferSize];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
m_Socket.receive(packet);
ProcessData(packet);
}
catch (IOException e)
{
if (!m_Socket.isClosed())
e.printStackTrace();
}
}
}
private void ProcessData(DatagramPacket packet)
{
if (packet.getLength() == 4)
{
ByteBuffer bb = ByteBuffer.wrap(packet.getData());
m_TotalLength = bb.getInt();
if (m_Received != 0)
m_FrameErrors++;
m_Received = 0;
m_Buffer = new byte[m_TotalLength];
}
else if (m_Buffer != null && m_Received != m_TotalLength)
{
int length = packet.getLength();
System.arraycopy(packet.getData(), 0, m_Buffer, m_Received, length);
m_Received += length;
m_Progress = 100 * (float)m_Received/(float)m_TotalLength;
if (m_Received == m_TotalLength)
{
m_Result = new byte[m_TotalLength];
System.arraycopy(m_Buffer, 0, m_Result, 0, m_TotalLength);
m_IsNewResult = true;
m_ImageCount++;
m_Received = 0;
}
}
}
public Boolean IsNewResult()
{
return m_IsNewResult;
}
public byte[] GetResult()
{
m_IsNewResult = false;
return m_Result;
}
public float GetProgress()
{
return m_Progress;
}
public float GetRatio()
{
return 100 * (float)m_ImageCount / (float)m_FrameErrors;
}
public void stopServer()
{
m_End = true;
if (m_Socket != null)
m_Socket.close();
}
}
And i am using this class like this:
package com.example.urowatch;
import java.io.IOException;
import java.text.DecimalFormat;
import android.os.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
public class LiveActivity extends Activity {
private static ImageView m_ImageView1;
private static TextView m_TextView1;
private static DecimalFormat m_DF;
private static Context m_Context;
private UDPReceiver m_Receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
// Show the Up button in the action bar.
setupActionBar();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
m_ImageView1 = (ImageView)findViewById(R.id.imageView1);
m_TextView1 = (TextView)findViewById(R.id.textView1);
m_Context = this;
m_DF = new DecimalFormat("00.00");
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.live, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private static Handler MyHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == 100)
{
float[] infos = (float[])msg.obj;
m_TextView1.setText("Empfange Bild: " + m_DF.format(infos[0]) + "% (FrameErrors: " + m_DF.format(infos[1]) + "%)");
}
else if (msg.what == 101)
{
byte[] b = (byte[])msg.obj;
m_TextView1.setText("Empfange Bild: 100,00%");
m_ImageView1.setImageBitmap(BitmapFactory.decodeByteArray(b, 0, b.length));
}
else if (msg.what == 102)
{
AlertDialog.Builder b = new AlertDialog.Builder(m_Context);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + (Exception)msg.obj);
b.setNeutralButton("OK", null);
b.show();
}
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
if (m_Receiver != null)
m_Receiver.stopServer();
finish();
}
#Override
public void onPause()
{
m_Receiver.stopServer();
super.onPause();
}
#Override
protected void onResume()
{
try {
m_Receiver = new UDPReceiver("UDPReceiver", 5678, 1024);
m_Receiver.start();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + e1);
b.setNeutralButton("OK", null);
b.show();
}
// Thread thread = new Thread()
// {
// #Override
// public void run()
// {
// while(true)
// {
// try {
//sleep(250);
Toast.makeText(getBaseContext(), "Runing Thread", Toast.LENGTH_SHORT).show();
Update();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// MyHandler.sendMessage(MyHandler.obtainMessage(102, e));
// }
// }
// }
// };
// thread.start();
super.onResume();
}
public void buttonClick(View v)
{
Update();
}
private void Update()
{
if (m_Receiver != null)
{
if (m_Receiver.IsNewResult())
{
byte[] b = m_Receiver.GetResult();
MyHandler.sendMessage(MyHandler.obtainMessage(101, b));
}
else
{
float[] infos = new float[2];
infos[0] = m_Receiver.GetProgress();
infos[1] = m_Receiver.GetRatio();
MyHandler.sendMessage(MyHandler.obtainMessage(100, infos));
}
}
}
}
As you see i want to check the status of the UDPReceiver-Object (Is there a new complete byte[] ready?) by a thread. To update the GUI, the thread has to send a Message to MyHandler which will update the GUI.
In the moment i have to to click a button to raise the buttonClick-Event. Later on i want to do this in the commented thread-structure.
Now, here's my problem:
I start the Activity and everything works fine. Then i am starting to send ONE packet manually with my UDP-Sender (which works, i validated it with a C#-UDP-Receiver). The first packet get received fine. Then i send the second packet which get received, too. But from now on, my breakpoint at m_Socket.receive(packet); wont get hit anymore!
I have NO idea what this behaviour causes and it is very important for me to make this application work.
Please, if you have ANY Idea or just a guess, please let me know.

Oauth Connectivity for twitter

private static String CONSUMER_KEY = "mrnCC41nxtwkdFAmToEhtg";
private static final String CONSUMER_SECRET = "kmmVuahEspGvdl14aCD1GSBZpeHbxvkpAez7aKaaQ";
EditText editPinCode;
LinearLayout lin;
public Logger slr;
LinearLayout container;
public LoginT(){
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter);
editPinCode = new EditText(this);
lin = (LinearLayout)findViewById(R.id.LinearLayout01);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
getTwitter(context);
}
/**
* Connects to twittter
* #param v
*/
public void getTwitter(Context ctx) { //updated code
handleEvent.post(new Runnable() {
// handleEvent.postAtFrontOfQueue(new Runnable() {
public void run() {
if (oHelper.hasAccessToken())
{
Log.e("run if","run");
oHelper.configureOAuth(twitterConnection);
try
{
i=i+1;
Log.e("run try","run");
twitterConnection.updateStatus(Calendar.MINUTE+i+"Hi this is Arun......");
//twitterConnection.se
Log.e("finish","start");
finish();
Log.e("finish","end");
}
catch (TwitterException e)
{
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
}
else
{
Log.e("run else","run");
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
requestToken = twitterConnection.getOAuthRequestToken("");
Log.e("REQUEST_TOKEN",requestToken+"");
webViewDialog(requestToken.getAuthorizationURL(), 0);
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
}});
}
/**
* Shows Dialog for authentications
*
* #param authorizationURL
* #param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
Log.e("webViewDialog","webViewDialog");
container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
// webView.dispatchWindowFocusChanged(true);
webView.setWebViewClient(new MyWebViewClient(this,LoginT.this));
webView.loadUrl(authorizationURL);
container.addView(webView);
lin.addView(container);
// Builder webDialog = new AlertDialog.Builder(this);
// webDialog.setView(container).setTitle("Twitter Client").setCancelable(true)
// .show();
}
/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
try {
// accessToken = twitterConnection.getOAuthAccessToken(requestToken,ss);
try{
accessToken = twitterConnection.getOAuthAccessToken(requestToken);
}
catch(Exception e1){
Log.w("Excep e1",e1+"");
}
oHelper.storeAccessToken(accessToken);
Log.w("ohelper",oHelper.toString());
twitterConnection.updateStatus("Tweeted Successfully"+new Date().toString());
Log.e(" ","2 "+accessToken);
Log.e(" ","3");
webView.destroy();
webView.removeAllViews();
container.removeAllViews();
this.finish();
// Log.i("Access Token:", accessToken.getToken());
// Log.i("Access Secret:", accessToken.getTokenSecret());
} catch (TwitterException te) {
oHelper.storeAccessToken(accessToken);
try {
twitterConnection.updateStatus("HI.... ");
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id) {
// case DIALOG_LOADING:
// {
// // dialog = new ProgressDialog(this);
// dialog.setMessage("Please wait while loading...");
// dialog.setIndeterminate(true);
// dialog.setCancelable(true);
// return dialog;
// }
}
return null;
}
//
// #Override
public void dismiss() {
Log.w("dismiss","dismiss");
try{
// webView.destroy();
// webView.removeAllViews();
// container.removeAllViews();
// this.finish();
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
//
#Override
public boolean onSearchRequested() {
Log.e("Search","Search");
return super.onSearchRequested();
}
I use the above Code for making connection for twitter but it only works for one time if I want another time for connection then it never provide me second time connection.
Thankx
Could this be an Activity lifecycle issue? Your call to getTwitter() occurs in onCreate, which only gets called when the Activity is created. If a user navigates away then comes back to your app, it may still be running, so onCreate would not get called again. Have a look at the Activity lifecycle, and add some debug code to each of the lifecycle methods (onResume, onPause etc) to get an idea of when they are called.

Categories

Resources