Wifi Printing in android is not working -


i have made android app printing pdf file using printer connected wifi. have tried per below code, searching devices nothing happened. please see code , tell me changes should solve problem. inputs appreciated!

code

public class mainactivity extends activity {      public int pageheight;     public int pagewidth;     public pdfdocument mypdfdocument;     public int totalpages = 4;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.main);      }      public class myprintdocumentadapter extends printdocumentadapter {         context context;          public myprintdocumentadapter(context context) {             this.context = context;          }          @suppresslint("inlinedapi")         @override         public void onlayout(printattributes oldattributes,                 printattributes newattributes,                 cancellationsignal cancellationsignal,                 layoutresultcallback callback, bundle metadata) {             mypdfdocument = new printedpdfdocument(context, newattributes);              pageheight = newattributes.getmediasize().getheightmils() / 1000 * 72;             pagewidth = newattributes.getmediasize().getwidthmils() / 1000 * 72;              if (cancellationsignal.iscanceled()) {                 callback.onlayoutcancelled();                 return;             }              if (totalpages > 0) {                 printdocumentinfo.builder builder = new printdocumentinfo.builder(                         "print_output.pdf").setcontenttype(                         printdocumentinfo.content_type_document).setpagecount(                         totalpages);                  printdocumentinfo info = builder.build();                 callback.onlayoutfinished(info, true);             } else {                 callback.onlayoutfailed("page count zero.");             }         }          @override         public void onwrite(final pagerange[] pageranges,                 final parcelfiledescriptor destination,                 final cancellationsignal cancellationsignal,                 final writeresultcallback callback) {             (int = 0; < totalpages; i++) {                 if (pageinrange(pageranges, i)) {                     pageinfo newpage = new pageinfo.builder(pagewidth,                             pageheight, i).create();                      pdfdocument.page page = mypdfdocument.startpage(newpage);                      if (cancellationsignal.iscanceled()) {                         callback.onwritecancelled();                         mypdfdocument.close();                         mypdfdocument = null;                         return;                     }                     drawpage(page, i);                     mypdfdocument.finishpage(page);                 }             }              try {                 mypdfdocument.writeto(new fileoutputstream(destination                         .getfiledescriptor()));             } catch (ioexception e) {                 callback.onwritefailed(e.tostring());                 return;             } {                 mypdfdocument.close();                 mypdfdocument = null;             }              callback.onwritefinished(pageranges);         }          private boolean pageinrange(pagerange[] pageranges, int page) {             (int = 0; < pageranges.length; i++) {                 if ((page >= pageranges[i].getstart())                         && (page <= pageranges[i].getend()))                     return true;             }             return false;         }          private void drawpage(pdfdocument.page page, int pagenumber) {             canvas canvas = page.getcanvas();              pagenumber++; // make sure page numbers start @ 1              int titlebaseline = 72;             int leftmargin = 54;              paint paint = new paint();             paint.setcolor(color.black);             paint.settextsize(40);             canvas.drawtext("test print document page " + pagenumber,                     leftmargin, titlebaseline, paint);              paint.settextsize(14);             canvas.drawtext(                     "this test content verify custom document printing works",                     leftmargin, titlebaseline + 35, paint);              if (pagenumber % 2 == 0)                 paint.setcolor(color.red);             else                 paint.setcolor(color.green);              pageinfo pageinfo = page.getinfo();              canvas.drawcircle(pageinfo.getpagewidth() / 2,                     pageinfo.getpageheight() / 2, 150, paint);         }     }      @suppresslint("inlinedapi")     public void printdocument(view view) {         printmanager printmanager = (printmanager)                 .getsystemservice(context.print_service);          string jobname = this.getstring(r.string.app_name) + " document";          printmanager.print(jobname, new myprintdocumentadapter(this), null);     }  } 

you can refer android-wifi-print - github. have created demo application printing.. flow.! bit.

with of following links have created this.

this flow of prototype.

  1. checks connectivity.
  2. if connected in wifi.. storing wifi configuration.
  3. now checking whether have printer's information (wifi configuration of wifi printer) available or not. if available, i'll scan , list of wifi scanresults , connects else.. it'll showing list of wifi , clicking on that, user connect printer , stores wifi configuration future printing jobs.
  4. after print job completes, i'm connecting previous wifi or mobile data connection.
  5. now going 2nd step.
  6. if user connected in mobile data, i'm enabling wifi , following 3rd step.
  7. after print job completes, i'm disabling wifi. that, we'll connected mobile data connection. (that android default).

if want print file call print(file) in printutility.class following class take care of printing jobs..

public class printutility implements observer {      private static final int time_out = 10000;     private static final int connection_time_out = 5000;      private activity mactivity;     private fragment mfragment = null;      private wificonfiguration mprinterconfiguration;     private wificonfiguration moldwificonfiguration;     private wifimanager mwifimanager;     private wifiscanner mwifiscanner;     private list<scanresult> mscanresults = new arraylist<scanresult>();      private printmanager mprintmanager;     private list<printjob> mprintjobs;     private printjob mcurrentprintjob;      private file pdffile;     private string externalstoragedirectory;      private handler mprintstarthandler = new handler();     private handler mprintcompletehandler = new handler();     private handler mwificonnecthandler = new handler();     private string connectioninfo;      private boolean ismobiledataconnection = false;      private printcompleteservice mprintcompleteservice;      //    observer pattern     private observable mobservable;       public printutility(activity mactivity, wifimanager mwifimanager, wifiscanner mwifiscanner) {         this.mactivity = mactivity;         this.mwifimanager = mwifimanager;         this.mwifiscanner = mwifiscanner;         mprintcompleteservice = (printcompleteservice) mactivity;         mobservable = observablesingleton.getinstance();         mobservable.attach(this);     }      public printutility(activity mactivity, fragment mfragment, wifimanager mwifimanager, wifiscanner mwifiscanner) {         this.mactivity = mactivity;         this.mfragment = mfragment;         this.mwifimanager = mwifimanager;         this.mwifiscanner = mwifiscanner;         mprintcompleteservice = (printcompleteservice) mfragment;         mobservable = observablesingleton.getinstance();         mobservable.attach(this);     }      public void downloadandprint(string fileurl, final string filename) {          new filedownloader(mactivity, fileurl, filename) {             @override             protected void onpostexecute(boolean result) {                  if (!result) {                     mobservable.notifyobserver(true);                 } else {                      // print flow come here.                      try {                         externalstoragedirectory = environment.getexternalstoragedirectory().tostring();                         file folder = new file(externalstoragedirectory, constants.controller_pdf_folder);                         pdffile = new file(folder, filename);                     } catch (exception e) {                         mobservable.notifyobserver(true);                         e.printstacktrace();                     }                      print(pdffile);                  }              }         }.execute("");     }      public void print(final file pdffile) {          this.pdffile = pdffile;          // check connectivity info -> mobile or wifi.         connectioninfo = util.connectioninfo(mactivity);          if (connectioninfo.equalsignorecase(constants.controller_mobile)) {             // follow mobile flow.             ismobiledataconnection = true;              if (mwifimanager.iswifienabled() == false) {                 mwifimanager.setwifienabled(true);             }              mwifimanager.startscan();             setscanresults(mwifiscanner.getscanresults());              printerconfiguration();          } else if (connectioninfo.equalsignorecase(constants.controller_wifi)) {             // follow wifi flow..              // current wifiinfo , store in shared preference.             util.storecurrentwificonfiguration(mactivity);              printerconfiguration();          } else {             mobservable.notifyobserver(true);         }      }      private void printerconfiguration() {          // check printer detail available or not.         mprinterconfiguration = util.getwificonfiguration(mactivity, constants.controller_printer);          if (mprinterconfiguration == null) {             // printer configuration not available.             // display list of wifi available in activity              showwifilistactivity(constants.request_code_printer);          } else {             // list of wifi available. if printer configuration available connect it.             // else.. show list of available wifi nearby.              boolean isprinteravailable = false;              // scans nearby wifi..             mwifimanager.startscan();             setscanresults(mwifiscanner.getscanresults());               // checks wifi in scan result list..             (int = 0; < mscanresults.size(); i++) {                 if (mprinterconfiguration.ssid.equals("\"" + mscanresults.get(i).ssid + "\"")) {                     isprinteravailable = true;                     break;                 }             }              if (isprinteravailable) {                  // connect printer wifi , show print settings dialog , continue print flow.                 connecttowifi(mprinterconfiguration);                  // prints document.                 doprint();              } else {                 showwifilistactivity(constants.request_code_printer);             }          }     }      private void showwifilistactivity(int requestcode) {         intent iwifi = new intent(mactivity, wifilistactivity.class);         mactivity.startactivityforresult(iwifi, requestcode);     }      private void connecttowifi(wificonfiguration mwificonfiguration) {         mwifimanager.enablenetwork(mwificonfiguration.networkid, true);     }      public void doprint() {          try {             // taking time connect printer.. used handler.. , waiting status.             mprintstarthandler.postdelayed(new runnable() {                 @override                 public void run() {                      mprintstarthandler.postdelayed(this, time_out);                      if (mprinterconfiguration.status == wificonfiguration.status.current) {                         if (mwifimanager.getconnectioninfo().getsupplicantstate() == supplicantstate.completed) {                              if (util.computepdfpagecount(pdffile) > 0) {                                 printdocument(pdffile);                             } else {                                  alertdialog.builder alert = new alertdialog.builder(mactivity);                                  alert.setmessage("can't print, page count zero.");                                  alert.setneutralbutton("ok", new dialoginterface.onclicklistener() {                                     @override                                     public void onclick(dialoginterface dialog, int i) {                                         dialog.dismiss();                                         switchconnection();                                     }                                 });                                  alert.show();                             }                         }                         mprintstarthandler.removecallbacksandmessages(null);                     } else {                         toast.maketext(mactivity, "failed connect printer!.", toast.length_long).show();                         switchconnection();                         mprintstarthandler.removecallbacksandmessages(null);                     }                 }             }, time_out);         } catch (exception e) {             e.printstacktrace();             toast.maketext(mactivity, "failed connect printer!.", toast.length_long).show();             switchconnection();         }     }      @targetapi(build.version_codes.kitkat)     public void printdocument(file pdffile) {          mprintmanager = (printmanager) mactivity.getsystemservice(context.print_service);          string jobname = mactivity.getresources().getstring(r.string.app_name) + " document";          mcurrentprintjob = mprintmanager.print(jobname, new printservicesadapter(mactivity, mfragment, pdffile), null);     }       @targetapi(build.version_codes.kitkat)     public void completeprintjob() {         mprintjobs = mprintmanager.getprintjobs();          mprintcompletehandler.postdelayed(new runnable() {             @override             public void run() {                  mprintcompletehandler.postdelayed(this, connection_time_out);                  if (mcurrentprintjob.getinfo().getstate() == printjobinfo.state_completed) {                      // remove printjob printmanager.                     (int = 0; < mprintjobs.size(); i++) {                         if (mprintjobs.get(i).getid() == mcurrentprintjob.getid()) {                             mprintjobs.remove(i);                         }                     }                      // switching previous connection..                     switchconnection();                      // stops handler..                     mprintcompletehandler.removecallbacksandmessages(null);                 } else if (mcurrentprintjob.getinfo().getstate() == printjobinfo.state_failed) {                     switchconnection();                     toast.maketext(mactivity, "print failed!", toast.length_long).show();                     mprintcompletehandler.removecallbacksandmessages(null);                 } else if (mcurrentprintjob.getinfo().getstate() == printjobinfo.state_canceled) {                     switchconnection();                     toast.maketext(mactivity, "print cancelled!", toast.length_long).show();                     mprintcompletehandler.removecallbacksandmessages(null);                 }              }         }, connection_time_out);     }      public void switchconnection() {         try {             if (!ismobiledataconnection) {                  moldwificonfiguration = util.getwificonfiguration(mactivity, constants.controller_wifi);                  // list of wifi available. if wifi configuration available connect it.                 // else.. show list of available wifi nearby.                 boolean iswifiavailable = false;                  // scans nearby wifi.                 mwifimanager.startscan();                 setscanresults(mwifiscanner.getscanresults());                  // checks wifi in scan result list.                 (int = 0; < mscanresults.size(); i++) {                     if (moldwificonfiguration.ssid.equals("\"" + mscanresults.get(i).ssid + "\"")) {                         iswifiavailable = true;                         break;                     }                 }                  if (iswifiavailable) {                      // connect printer wifi , show print settings dialog , continue print flow.                     connecttowifi(moldwificonfiguration);                      mwificonnecthandler.postdelayed(new runnable() {                         @override                         public void run() {                             mwificonnecthandler.postdelayed(this, time_out);                             if (moldwificonfiguration.status == wificonfiguration.status.current) {                                 if (mwifimanager.getconnectioninfo().getsupplicantstate() == supplicantstate.completed) {                                      try {                                         mobservable.notifyobserver(true);                                     } catch (exception e) {                                         e.printstacktrace();                                     }                                      mwificonnecthandler.removecallbacksandmessages(null);                                 }                             }                         }                     }, time_out);                  } else {                     showwifilistactivity(constants.request_code_wifi);                 }             } else {                 mwifimanager.setwifienabled(false);                 mobservable.notifyobserver(true);             }         } catch (exception e) {             mobservable.notifyobserver(true);             e.printstacktrace();         }     }      public void getprinterconfigandprint() {         mprinterconfiguration = util.getwificonfiguration(mactivity, constants.controller_printer);         doprint();     }      public void setscanresults(list<scanresult> scanresults) {         this.mscanresults = scanresults;     }      public void onprintcancelled() {         switchconnection();     }      @override     public void update() {         mobservable.detach(this);     }      @override     public void updateobserver(boolean bool) {      }      @override     public void updateobserverprogress(int percentage) {      }  } 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -