Wednesday, 16 July 2014
Friday, 4 July 2014
How to connect google cloud printer to print files from your Android tablet ? Simple steps :-)
The steps below describe how to set
up your local printer for use with Google Cloud Print:-
- 1. Launch Google Chrome on your computer.
- 2. Click the Menu button (represented by an icon showing 3 horizontal bars) at the upper- right corner of the window.
- 3. Select Settings.
- 4. Click Show advanced settings.
- 5. Scroll down to the Google Cloud Print section and click Add printers.
- 6. Log in to your Google Account to enter Google Cloud Print
- 7. A confirmation message appears on the next screen. This will register the printer that is connected to the computer. Click Add Printer(s) to confirm.
- 8. Your printer is now registered with Google Cloud Print
Application Requirements:-
1. Android.permission
1. INTERNET
2.
READ_EXTERNAL_STORAGE3. READ_INTERNAL_STORAGE
4. ACCESS_NETWORK_STATE
5. WRITE_EXTERNAL_STORAGE
2. Act_main.java (Main
launch-Activity)
3. PrintDialogActivity.java
(Activity for Google print setup)
4. Act_main.Xml (First
User View)
5. Print_dialog.xml (Google
print purpose)
6. Row.xml (List view
item)
******************************************************************************
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.manish.googleprintdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.manish.googleprintdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PrintDialogActivity" />
</application>
</manifest>
*****************************************************************************
act_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_select"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="Select File" />
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="277dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:weightSum="3" >
<TextView
android:id="@+id/Sel_item"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:gravity="center"
android:text="Selected File :" />
<Button
android:id="@+id/btn_print"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Print" />
</LinearLayout>
</LinearLayout>
********************************************************************************
Print_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
*********************************************************************************
Row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
*********************************************************************************
Act_main.java
package com.example.filesgoogleprint;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class act_main extends ListActivity {
Button btn_select,btn_print;
ListView list;
TextView Sel_item;
private List<String> item = null;
private List<String> path = null;
private String root="/";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
init();
btn_select.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getDir(root);
}
});
btn_print.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isNetworkAvailable() == false) {
Toast.makeText(act_main.this,
"Network connection not available, Please try later",
Toast.LENGTH_SHORT).show();
} else {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + Sel_item.getText().toString());
Intent printIntent = new Intent(act_main.this, PrintDialogActivity.class);
printIntent.setDataAndType(Uri.fromFile(file), "application/pdf");
printIntent.putExtra("title", "Android print demo");
startActivity(printIntent);
}
}
});
}
private void init() {
// TODO Auto-generated method stub
btn_select=(Button)findViewById(R.id.btn_select);
Sel_item=(TextView)findViewById(R.id.Sel_item);
btn_print=(Button)findViewById(R.id.btn_print);
}
private void getDir(String dirPath)
{
Sel_item.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
Sel_item.setText(/*path.get(position)+"" +*/ "/"+file.getName());
Sel_item.setTextSize(20);
Log.v("/xyz.pdf", file.getName());
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("["+path.get(position)+"" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
Log.e("Network Testing", "***Available***");
return true;
}
Log.e("Network Testing", "***Not Available***");
return false;
}
}
********************************************************************************
PrintDialogActivity.java
package com.manish.googleprintdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class PrintDialogActivity extends Activity {
private static final String PRINT_DIALOG_URL = "https://www.google.com/cloudprint/dialog.html";
private static final String JS_INTERFACE = "AndroidPrintDialog";
private static final String CONTENT_TRANSFER_ENCODING = "base64";
private static final String ZXING_URL = "http://zxing.appspot.com";
private static final int ZXING_SCAN_REQUEST = 65743;
/**
* Post message that is sent by Print Dialog web page when the printing dialog
* needs to be closed.
*/
private static final String CLOSE_POST_MESSAGE_NAME = "cp-dialog-on-close";
/**
* Web view element to show the printing dialog in.
*/
private WebView dialogWebView;
/**
* Intent that started the action.
*/
Intent cloudPrintIntent;
@SuppressLint("JavascriptInterface") @Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.print_dialog);
dialogWebView = (WebView) findViewById(R.id.webview);
cloudPrintIntent = this.getIntent();
WebSettings settings = dialogWebView.getSettings();
settings.setJavaScriptEnabled(true);
dialogWebView.setWebViewClient(new PrintDialogWebClient());
dialogWebView.addJavascriptInterface(
new PrintDialogJavaScriptInterface(), JS_INTERFACE);
dialogWebView.loadUrl(PRINT_DIALOG_URL);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == ZXING_SCAN_REQUEST && resultCode == RESULT_OK) {
dialogWebView.loadUrl(intent.getStringExtra("SCAN_RESULT"));
}
}
final class PrintDialogJavaScriptInterface {
public String getType() {
return cloudPrintIntent.getType();
}
public String getTitle() {
return cloudPrintIntent.getExtras().getString("title");
}
public String getContent() {
try {
ContentResolver contentResolver = getContentResolver();
InputStream is = contentResolver.openInputStream(cloudPrintIntent.getData());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = is.read(buffer);
while (n >= 0) {
baos.write(buffer, 0, n);
n = is.read(buffer);
}
is.close();
baos.flush();
return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public String getEncoding() {
return CONTENT_TRANSFER_ENCODING;
}
public void onPostMessage(String message) {
if (message.startsWith(CLOSE_POST_MESSAGE_NAME)) {
finish();
}
}
}
private final class PrintDialogWebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(ZXING_URL)) {
Intent intentScan = new Intent("com.google.zxing.client.android.SCAN");
intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE");
try {
startActivityForResult(intentScan, ZXING_SCAN_REQUEST);
} catch (ActivityNotFoundException error) {
view.loadUrl(url);
}
} else {
view.loadUrl(url);
}
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
if (PRINT_DIALOG_URL.equals(url)) {
// Submit print document.
view.loadUrl("javascript:printDialog.setPrintDocument(printDialog.createPrintDocument("
+ "window." + JS_INTERFACE + ".getType(),window." + JS_INTERFACE + ".getTitle(),"
+ "window." + JS_INTERFACE + ".getContent(),window." + JS_INTERFACE + ".getEncoding()))");
// Add post messages listener.
view.loadUrl("javascript:window.addEventListener('message',"
+ "function(evt){window." + JS_INTERFACE + ".onPostMessage(evt.data)}, false)");
}
}
}
}
********************************************************************************
Subscribe to:
Posts (Atom)
How to do text writing animation? In Android Development we do not have the option to use any other custom font in our default Tex...
-
Smartphone notifications are pretty useful, there's no denying that. They make it hard to miss an important event, such as an upcom...
-
Microsoft Translator is a hosted service, accessed via an API that provides language translation. It can be used to build Android Applicat...
-
Text To Speech It is a great piece of technology that was developed to help individuals with visual impairments. However, dev...