I want to cancel a downloading file using async task, i tried below code, here isCancelled() method is not working, can any one suggest how can i stop download.
vid1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
down d1=new down();
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
d1.execute(url1,"one");
}else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(d1!=null && d1.getStatus()!=AsyncTask.Status.FINISHED){
d1.cancel(true);
}
}
}
});
vid2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Vid 2", "Vid 2");
// TODO Auto-generated method stub
down d2=new down();
if(vid2.getText().toString().equals("Start")){
vid2.setText("Pause");
d2.execute(url2,"two");
}else if(vid2.getText().toString().equals("Pause")){
vid2.setText("Start");
Log.v("Vid 2 Else", "Vid 2 Else ");
d2.cancel(true);
}
}
});
}
private class down extends AsyncTask<String, Void, String>{
RandomAccessFile output ;
boolean cancel=false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Log.v("Pre Execute", "Pre Execute");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
File outputFileCache=new File(Environment.getExternalStorageDirectory()+"/pau/"+params[1]+".mp4");
try {
Long download_ok = null ;
int fileLength;
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection() ;
if (outputFileCache.exists())
{
Log.v(">>>>>>", "Exists");
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + outputFileCache.length() + "-");
}
connection.setConnectTimeout(14000);
connection.setReadTimeout(20000);
connection.connect();
if (connection.getResponseCode() / 100 != 2)
throw new Exception("Invalid response code!");
else
{
String connectionField = connection.getHeaderField("content-range");
if (connectionField != null)
{
String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
download_ok = Long.valueOf(connectionRanges[0]);
Log.v("download ok", ""+download_ok);
}
if (connectionField == null && outputFileCache.exists())
outputFileCache.delete();
if(download_ok==null){
download_ok=(long) 0;
}
fileLength = (int) (connection.getContentLength() + download_ok);
Log.v("file length", ""+fileLength);
input = new BufferedInputStream(connection.getInputStream());
output = new RandomAccessFile(outputFileCache, "rw");
output.seek(download_ok);
byte data[] = new byte[1024];
int count = 0;
int __progress = 0;
while ((count = input.read(data, 0, 1024)) != -1 && __progress!=100)
{
Log.v(">>>>>>>>>>>progress cancelled", "<<<<<<<<<"+isCancelled());
if(isCancelled()){
Log.v(">>>>>>>>>>>>>>>>>>>>>>>>>>>", "<<<<<<<<<"+isCancelled());
break;
}else{
download_ok += count;
output.write(data, 0, count);
__progress = (int) ((download_ok * 100) / fileLength);
}
}
output.close();
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
Found your problem: You are creating a new instance of the Asynctask with every click, e.g.
down d2=new down();
This means that you are calling cancel on a different AsyncTask object. You need to move this line into your check for the start click and also use a field and not a local variable i.e.
if(vid2.getText().toString().equals("Start")) {
d2 = new down();
vid2.setText("Pause");
d2.execute(url2,"two");
}
where d2 is set in your class. Also note that class names should always start with capital letters, i.e. class Down instead of class down.
EDIT
You can store the Asynctask in a global class array that is equal in length to the number of videos.
Down downTasks[] = new Down[TOTAL VIDEOS];
Then you initialise the Views, similar to what you already did, here shown for one View
vid1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
downTasks[0] = new down();
downTasks[0].execute(url1,"one");
}
else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(downTasks[0]!=null && downTasks[0].getStatus()!=AsyncTask.Status.FINISHED){
downTasks[0].cancel(true);
}
}
}
});
Note that this code is quite redundant because you rewrite almost exactly the same code for every View, this can be nicely refactored with a for loop, but I leave that as an exercise for you if you feel like it.
Related
I have two objects, a establishment object that belongs to a deal object that can be voted upon. If I up/down vote the same deal multiple times, the seventh time I vote the query just sits and does not do anything. The app does not crash, but it also does not save. If I go into another activity that requires a parse.com query that query also will not work. Here is my up vote logic (down voting is identical).
Assume all vars used are initialized before onCreate().
Are my queries getting backed up in a pipe somewhere?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upVoteButton = (Button) findViewById(R.id.deal_up_vote_button);
upVoteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new UpVoteTask().execute();
}
});
}
// visually changes buttons if they are selected
private void setButtons(Boolean queryDb) {
if (queryDb == true) {
queryParse();
}
// if deal found correctly
if (deal != null) {
// if user found correctly
if (dealVoteUser != null) {
if (dealVoteUser.get("vote").toString().equals("0")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(true);
} else if (dealVoteUser.get("vote").toString().equals("1")) {
upVoteButton.setPressed(true);
downVoteButton.setPressed(false);
} else if (dealVoteUser.get("vote").toString().equals("2")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(false);
}
}
}
}
// queries parse and populates vars
private void queryParse(){
ParseQuery<ParseObject> queryDeal = ParseQuery.getQuery("Deal");
queryDeal.whereEqualTo("objectId", deal_id);
try {
deal = queryDeal.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParseQuery<ParseObject> queryDealVoteUser = ParseQuery
.getQuery("deal_vote_users");
queryDealVoteUser.whereEqualTo("deal", deal).whereEqualTo("user",
ParseUser.getCurrentUser());
try {
dealVoteUser = queryDealVoteUser.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// UpVoteTask AsyncTask
private class UpVoteTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
upVoteProgressDialog = new ProgressDialog(DealsDetailsActivity.this);
// Set progressdialog message
upVoteProgressDialog.setMessage("Saving...");
upVoteProgressDialog.setIndeterminate(false);
// Show progressdialog
upVoteProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
queryParse();
// if deal found correctly
if (deal != null) {
// if user has not voted yet
if (dealVoteUser == null) {
// create new and assign vote to 1
dealVoteUser = new ParseObject("deal_vote_users");
dealVoteUser.put("deal", deal);
dealVoteUser.put("user", ParseUser.getCurrentUser());
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
// if user already down voted
} else if (dealVoteUser.get("vote").toString().equals("0")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes") - 1;
// if user already up voted
} else if (dealVoteUser.get("vote").toString().equals("1")) {
// already voted up, remove vote
dealVoteUser.put("vote", 2);
up_votes = deal.getInt("up_votes") - 1;
down_votes = deal.getInt("down_votes");
// if user already voted but cleared vote
} else if (dealVoteUser.get("vote").toString().equals("2")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
}
// calculate overall rating percentage
if ((up_votes + down_votes) != 0) {
rating = (up_votes / (up_votes + down_votes)) * 100;
} else if ((up_votes == 0) && (down_votes == 0)) {
rating = 0;
} else {
rating = 50;
}
deal.put("rating", rating);
deal.put("up_votes", up_votes);
try {
deal.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dealVoteUser.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// deal not found problem
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// visually change buttons without querying db
setButtons(false);
//remove progress dialogue
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
}
}
Use the saveInBackground method - it will do the same as save, but also save it to your application's cache so that you won't get different values while the data is being saved, so it won't have any apparent effect on your application. It's the best method to save or find (it has a 'sister' method named findInBackground). It acts like an Async task and does not clog your main thread.
I switched all parse calls over to ._____InBackground() and I moved the save logic to onPause(). This way I am not making multiple save calls to parse if the user decides to change their vote multiple times.
I am developing an app that downloads files and show 2 progress bars, the first one for the current downloading file, and the 2nd one for total progress based on the number of files.
I am using the DoubleProgressBar library in my app:
I succeeded to update the first ProgressBar, but stuck with the 2nd one.
Here is my code for the AsyncTask class:
private DoubleProgressDialog pDialog;
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
Context mContext;
public DownloadFileFromURL(Context ctx) {
// TODO Auto-generated constructor stub
this.mContext = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(CUSTOM_PROGRESS_DIALOG);
}
/* Downloading file in background thread */
#Override
protected String doInBackground(String... f_url) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(f_url[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// getting file length
int fileLength = connection.getContentLength();
for (int i = 0; i <= ArrayOfFiles.length; i++){
File f = new File(Environment.getExternalStorageDirectory() + "/Folder/", ArrayOfFiles[i]);
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
output = new FileOutputStream(f);
byte data[] = new byte[8192];
long total = 0;
int count;
int EntireProgress = 0;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
/*Here is my trouble, the 2nd ProgressBar is updating as the same of the first one, I need the 2nd one to update itself slowly till all files get downloaded*/
int CurrentProgress = pDialog.getProgress();
pDialog.setSecondaryProgress(CurrentProgress );
publishProgress(CurrentProgress );
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
}
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// dismiss the dialog after the file was downloaded
dismissDialog(CUSTOM_PROGRESS_DIALOG);
if (result != null)
Toast.makeText(mContext,"Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(mContext,"File downloaded", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(progress[0]);
}
}
I also used this method in my activity class:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CUSTOM_PROGRESS_DIALOG:
pDialog = new DoubleProgressDialog(NetworkActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setMax(100);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
pDialog.show();
return pDialog;
default:
return null;
}
}
Any idea?
First part is to move pDialog.setSecondaryProgress to the onProgressUpdate(Integer... progress) method.
You are also resetting the secondary progress in each download task by setting it to CurrentProgress which is set to pDialog.getProgress();. Hence the second progress will always be reset after the download is finished.
Edit:
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int)(total * 100 / fileLength), pDialog.getSecondaryProgress());
(...)
int CurrentProgress = pDialog.getProgress();
// do not update secondary progress here
// pDialog.setSecondaryProgress(CurrentProgress );
int secondaryProgress = (CurrentProgress + 100 * i)/ArrayOfFiles.length;
publishProgress(CurrentProgress, secondaryProgress);
And the onProgressUpdate
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
(...)
pDialog.setProgress(progress[0]);
pDialog.setSecondaryProgress(progress[1]);
}
If you are not setting your DownloadFileFromUrl outside your main class I would suggest something like this
int CurrentProgress = pDialog.getProgress();
int secondaryProgress = (CurrentProgress + 100 * id_treated_file)/number_of_files;
// id_treated_file - 0, 1, 2, ... , number_of_files - 1
pDialog.setSecondaryProgress(CurrentProgress);
// secondaryProgress will be progress[1] in your onProgressUpdate method
publishProgress(CurrentProgress, secondaryProgress);
your onProgressUpdate method should look like this :
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(progress[0]);
pDialog.setSecondaryProgress(progress[1]);
}
EDIT
or you can try
pDialog.setSecondaryProgress((progress[0] + 100 * id_treated_file)/number_of_files);
I am trying to download some xml files through this code.
Everything works fine when network is available.I have already handled the issue when network is not at all there. But the issue m facing right now is that ,when network is slow ,the download doesnt timeout.
Time out is not at all working ,I think.How to make it work?
URL mUrl = new URL(url[i]);
URLConnection conexion = mUrl.openConnection();
response[i] = new DownloadResponse();
response[i].setSuccessful(false);
conexion.connect();
conexion.setConnectTimeout(10000);
// this will be useful so that you can show a typical 0-100% progress bar
ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
if (outputFile != null) { // one output file specified in constructor
output = new BufferedOutputStream(new FileOutputStream(
outputFile));
} else if (outputFiles != null) { // an array of output files specified
output = new BufferedOutputStream(new FileOutputStream(
outputFiles[i]));
} else {// no output file specified
output = new BufferedOutputStream(outBytes);
}
InputStream input = new BufferedInputStream(mUrl.openStream());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
response[i].setSuccessful(true);
response[i].count = i;
response[i].setResponseText(outBytes.toString());
if (total < 32 && outBytes.toString().indexOf("Invalid") < -1){
response[i].setSuccessful(false);
}
output.close();
input.close();
publishProgress(response[i]);
in onclick whendownload button
define globally in class boolean b = true;
count_Timer = new CountDownTimer(20000, 1000) {
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
b = false;
pd.dismiss();
dialog.dismiss();
AlertDialog.Builder builder1 = new AlertDialog.Builder(
AppSetting.this);
builder1.setTitle("appname");
builder1.setMessage("You can't Continue because internet is Very slow.");
builder1.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
});
builder1.show();
}
};
on beginning of download task
count_Timer.start();
on last line of doinbackground
count_Timer.cancel();
and on postexecute method
if (pd.isShowing())
pd.dismiss();
if (b) {
dialog.dismiss();
simplealert(result.replace("\"", ""));
} else {
}
I am working on Android app.
I need to show a progress dialog box when I click on button.
In that button I am converting video file to .zip file and calculating that file size.
In this process I need to show a ProgressDialog, but it is not showing.
Screen get struck while calculating and after calculation it shows ProgressDialog and then screen navigating to the next screen.
My Code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaCheck.this.runOnUiThread(new Runnable() {
public void run() {
pd = ProgressDialog.show(MediaCheck.this, "",
"Checking the video compatability. Please wait", true);
}
});
video_Path= makeZip(video_Path);
if (video_Path.equalsIgnoreCase("File size is too large")) {
pd.dismiss();
Toast.makeText(getApplicationContext(),
"Large video", Toast.LENGTH_LONG)
.show();
return;
}
pd.dismiss();
// Doing screen navigation here.
}
});
Code to make a zip and know the size
private static String makeZip(String videoPath) {
byte[] buffer = new byte[1024];
String[] videoFileName = videoPath.split("/");
File directory = null;
try {
ContextWrapper cw = new ContextWrapper(context_this);
// path to /data/data/yourapp/app_data/imageDir
directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
FileOutputStream fos = new FileOutputStream(directory
+ "/IRCMS_Video.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = null;
ze = new ZipEntry(videoFileName[5]);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(videoPath);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
File videoZip = new File(directory + "/IRCMS_Video.zip");
videoLength = videoZip.length() / (1024 * 1024);
if (videoLength > 3)
return "File size is too large";
in.close();
zos.closeEntry();
// remember close it
zos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
return directory.toString() + "/IRCMS_Video.zip";
}
}
Please help...
then you should try ASYNCTASK to easily perform your operation and reduce the complexity of using threads
private class Converter extends AsyncTask<String, Void, Void> { //Converter is class name
protected String doInBackground(String... urls) {
//THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
//YOUR NETWORK OPERATION HERE
return null;
}
protected void onPreExecute() {
super.onPreExecute();
//THIS METHOD WILL BE CALLED FIRST
//DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
}
protected void onPostExecute(String result) {
super.onPostExecute();
//TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
//DO OPERATION LIKE UPDATING UI HERE
}
}
You are doing calculation on UI thread therfore it hangs your app. Do calculation on background thread. You can resolve this by-
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pd = ProgressDialog.show(MediaCheck.this, "",
"Checking the video compatability. Please wait", true);
Thread background = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
video_Path= makeZip(video_Path);
MediaCheck.this.runOnUiThread(new Runnable()
{
public void run()
{
if (video_Path.equalsIgnoreCase("File size is too large")) {
pd.dismiss();
Toast.makeText(getApplicationContext(),
"Large video", Toast.LENGTH_LONG)
.show();
pd.dismiss();
return;
}
}
});
}
});
background.start();
// Doing screen navigation here.
}
});
very rare do i come here because most of my problems are solved with examples and samples ect. which im not to bad with. now my problem is i cant figure out what the hell is going on. So i bought this printer, i got the SDK,
In the sdk once i load it, i have to press connect, and it pairs and i punch in the pin (0000), once that done, i get the test button to show up and prints the string ect ect.
what i want it to do is, Connect to the printer (automatically or with a pin, whatever)
Then press "next activity" and be able to print in the next activity whatever i want to with the Bluetooth printer. but when the next activity loads, the connection is closed and i cannot use the printer UNLESS i create the connection method into that activity all together where i would need to pair the device over and over and over again. so here is my SDK that i got. i really hope someone can help me because im going freakin go nuts, i tried using getbondeddevices but i dont think im clever enough... so here goes. maybe someone can see how the printer connects and how i can share it throughout the activities??
maybe even a tutorial on how to pair a device and then use it in the next activity... any help would be great
public class PrintTestAcitvity extends Activity {
// btOperation bo = new btOperation();
//// ¶ÔÆ뷽ʽ
/**
* printing text align left
*/
public static final int AT_LEFT = 0;
/**
* printing text align center
*/
public static final int AT_CENTER = 1;
/**
* printing text align right
*/
public static final int AT_RIGHT = 2;
private static final String GetBondedDevice = null;
// public String curentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
public static String curentDateTimeString() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
private Button btConnect = null;
private Button btCancel = null;
private Button asciiSend = null;
private Button graphicSend = null;
private regoPrinter mobileprint = null;
private boolean bConnect = true;
private TextView textTitle = null;
// private EditText portName;
private int iObjectCode;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btConnect = (Button)findViewById(R.id.connect);
btCancel = (Button)findViewById(R.id.cancel);
asciiSend = (Button)findViewById(R.id.asc_send);
graphicSend = (Button)findViewById(R.id.gra_send);
textTitle = (TextView)findViewById(R.id.title);
// portName = (EditText)findViewById(R.id.portName);
iObjectCode = 0;
mobileprint = new regoPrinter();
asciiSend.setEnabled(false);
graphicSend.setEnabled(false);
btConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String strName = "MPT-II"; // portName.getText().toString();
if(strName.length() == 0)
{
Toast.makeText(PrintTestAcitvity.this, "Error:port name empty", Toast.LENGTH_SHORT).show();
return;
}
if(bConnect)
{
try
{
mobileprint.CON_LnitPrintLib();
iObjectCode = mobileprint.CON_ConnectDevice(strName);
}
catch(printLibException e)
{
Toast.makeText(PrintTestAcitvity.this, e.GetMessage(),
Toast.LENGTH_LONG).show();
}
finally
{
if(iObjectCode != 0)
{
// connect succeed
textTitle.setText(strName + PrintTestAcitvity.this.getString(R.string.consucceed));
btConnect.setText(R.string.disconnect);
bConnect = false;
asciiSend.setEnabled(true);
graphicSend.setEnabled(true);
}
}
}
else
{
textTitle.setText(strName + PrintTestAcitvity.this.getString(R.string.disconnect));
asciiSend.setEnabled(false);
graphicSend.setEnabled(false);
try {
mobileprint.CON_CloseConnect(iObjectCode);
} catch (printLibException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bConnect = true;
btConnect.setText(R.string.connect);
}
}
});
btCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!bConnect)
{
try {
mobileprint.CON_CloseConnect(iObjectCode);
} catch (printLibException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mobileprint.CON_FreePrintLib();
finish();
return;
}
});
asciiSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
// mobileprint.CON_PageStart(iObjectCode, 576, 0) &&
if(mobileprint.ASCII_QueryPrinterStatus(iObjectCode))
{
//Çå³ý´òÓ¡»ú»º³å
mobileprint.ASCII_Reset(iObjectCode);
//´òÓ¡LogoͼƬ£¬ÏȽ«Í¼Æ¬ÏÂÔØÖÁ´òÓ¡»úÖÐÔÙÖ´Ðд˺¯Êý
//mobileprint.PrintFlashPic(1, 0);
//´òÓ¡title
mobileprint.ASCII_AlignType(iObjectCode, 1);
mobileprint.ASCII_FormatString(iObjectCode,false,false,true,false,false);
mobileprint.ASCII_SendString(iObjectCode, "Plate:" +" " + "ABCD123", "gb2312");
// mobileprint.ASCII_PrintCRLF(iObjectCode, 2);
mobileprint.ASCII_FeedLines(iObjectCode, 1);
mobileprint.ASCII_Reset(iObjectCode);
mobileprint.ASCII_PrintCRLF(iObjectCode, 2);
mobileprint.CON_PageEnd(iObjectCode);
}
else
{
Toast.makeText(PrintTestAcitvity.this, "Printer status error",
Toast.LENGTH_LONG).show();
}
} catch (printLibException e) {
// TODO Auto-generated catch block
Toast.makeText(PrintTestAcitvity.this, e.GetMessage(),
Toast.LENGTH_LONG).show();
}
}
});
graphicSend.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if(mobileprint.CON_PageStart(iObjectCode, 576, 450) && mobileprint.ASCII_QueryPrinterStatus(iObjectCode))
{
//Çå³ý´òÓ¡»ú»º³å
mobileprint.ASCII_Reset(iObjectCode);
mobileprint.DRAW_Line(iObjectCode,0, 1, 575, 1,3);
mobileprint.DRAW_Line(iObjectCode,0, 1, 0, 450,3);
mobileprint.DRAW_Line(iObjectCode,575, 1, 575, 450,3);
mobileprint.DRAW_Line(iObjectCode,0, 450, 575, 450,3);
mobileprint.DRAW_Line(iObjectCode,465, 1, 465, 450,1);
mobileprint.DRAW_Rectangle(iObjectCode, 0, 0, 80, 50, 1, true);
/* mobileprint.DRAW_Text(iObjectCode, 30, 80, "ÉϺ£¿ì½Ý¿ìÔËÓÐÏÞ¹«Ë¾ ", 40);
mobileprint.DRAW_Text(iObjectCode,90, 185, "ÉϺ£ -> ±±¾©", 35);
mobileprint.DRAW_Text(iObjectCode,80, 245, "(ÉϺ£±±Ç๫·°ì)", 20);
mobileprint.DRAW_Text(iObjectCode,310, 245, "(»ðʮ·վ)", 20);
mobileprint.DRAW_Text(iObjectCode,20, 305, "20112-02100100-0101-2112-10", 30);
mobileprint.DRAW_Code128(iObjectCode, 60, 350, 1, 60, "754432112-2");
mobileprint.DRAW_CreateRotalBlock(iObjectCode,476, 0, 450,100, 2);//(0.0) Ϊ×óÉϽǵľØÐÎ
mobileprint.DRAW_Code128(iObjectCode, 40, 5, 1, 60, "754432112-2");
*/
mobileprint.CON_PageEnd(iObjectCode);
}
else
{
Toast.makeText(PrintTestAcitvity.this, "Printer status error",
Toast.LENGTH_LONG).show();
}
} catch (printLibException e) {
// TODO Auto-generated catch block
Toast.makeText(PrintTestAcitvity.this, e.GetMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
}