In android, can we add printer plugins inside application memory or there jar file inside asset folder, and try to call it from application, to create mobile printing.
As I find
> Print Share Application option only. Any other way without Google cloud or any cloud printing.
This is working for me,I am passing pdf file to printer it is
printing!!
class WifiPrint extends Activity { TextView printer_name, gate_way,
printer_port; int port = 9100; WifiManager wifi = null;
android.net.DhcpInfo d; String gateway_ip = "";
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_print); wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE); printer_name = (TextView)
findViewById(R.id.textView1); gate_way = (TextView)
findViewById(R.id.textView2); printer_port = (TextView)
findViewById(R.id.textView3);
/* de.lohndirekt.print.IppPrintService svc = new IppPrintService(printerURI); InputStream stream = new
BufferedInputStream(new FileInputStream("image.epl")); DocFlavor
flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc myDoc = new
SimpleDoc(stream, flavor, null); DocPrintJob job =
svc.createPrintJob(); job.print(myDoc, null);*/
}
#Override public boolean onCreateOptionsMenu(Menu menu) { //
Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.wifi_print, menu); return true;
}
public void wifisettings(View v) { startActivityForResult(new
Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS), 0); }
public void connectSocket(View v) {
/*Uri filepath=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pdfsample); Toast.makeText(this, filepath.getPath(), Toast.LENGTH_LONG).show(); */ ClientThread clientThread = new
ClientThread(""); Thread clientstartThread = new
Thread(clientThread); clientstartThread.start(); }
public String intToIp(int i) { return ((i & 0xFF) + "." + ((i >> 8)
& 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + ((i >> 24) & 0xFF)); }
#Override protected void onActivityResult(int requestCode, int
resultCode, Intent data) { // TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data); if
(requestCode == 0) { WifiInfo wifiinfo = wifi.getConnectionInfo();
d = wifi.getDhcpInfo();
printer_name.setText("Name:" + wifiinfo.getSSID()); gateway_ip =
intToIp(d.gateway); gate_way.setText("Printer Ip:" + gateway_ip);
printer_port.setText("Port:" + port);
} }
public File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("/sdcard/testpdf.pdf");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null; }
class ClientThread implements Runnable { String filepath = "";
BufferedInputStream bis = null; FileInputStream fis;
Socket socket;
public ClientThread(String filename) { filepath = filename; }
#Override public void run() { // TODO Auto-generated method
stub try {
InputStream in = getResources().openRawResource(R.raw.pdfsample);
createFileFromInputStream(in);
File pdfFile = new File("/sdcard/testpdf.pdf");
byte[] mybytearray = new byte[(int) pdfFile.length()];
socket = new Socket(gateway_ip, port);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(socket.isConnected()){
Toast.makeText(WifiPrint.this,
"Socket Connected",
Toast.LENGTH_LONG).show();
}
}
});
fis = new FileInputStream(pdfFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (bis != null) {
bis.close();
os.close();
socket.close();
fis.close();
}
} catch (final UnknownHostException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"UnHost Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"Io Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } finally {
try {
if (bis != null) {
bis.close();
socket.close();
fis.close();
}
} catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(
WifiPrint.this,
"Io Exeption in Closing Socket"
+ e.getMessage(), Toast.LENGTH_LONG)
.show();
}
});
} } }
}
}
In manifest file : just add:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.wifi" />
Yes!!!
In Android 4.4 (API level 19) and higher, the framework provides services for printing images and documents directly from Android applications.
/**
* To print image / photo
*/
private void printPhoto() {
// Get a PrintHelper instance
PrintHelper photoPrinter = new PrintHelper(this);
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
// get image from mipmap folder
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
// provide job name (which will be displayed in the print queue) and bitmap
photoPrinter.printBitmap("droids.jpg - test print", bitmap);
}
Reference for print html and custom document
Related
I have tried many example and did not find any good solution.
I want to store the data of my app to store in sqlite database then sync it with the google drive account of the user who installed the app.
There is also a button which will show the data from google drive and user can edit and update the data so the updated data is then store in the google drive.
I'm new in Android development please help me.
I also have applied the following example but did not succeed.
https://github.com/seanpjanson/GDAADemo
Create / Edit / Retrieve DB file with GDAA (Google Drive Api for Android)
Unpredictable result of DriveId.getResourceId() in Google Drive Android API
https://github.com/googledrive/android-quickstart
Thanks
first create a db backup in SD-card using below line
Driver_utils.create_backup(SettingActivity.this);
**add below dependencies in build.gradle **
compile 'com.google.code.gson:gson:2.2.+'
compile 'com.google.android.gms:play-services-drive:10.0.1'`
in_drive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Utils.isInternetWorking()) {
File directorys = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup");
if (directorys.exists()) {
String json = preferences_driverId.getString("drive_id", "");
DriveId driveId = gson.fromJson(json, DriveId.class);
//Update file already stored in Drive
Driver_utils.trash(driveId, google_api_client);
// Create the Drive API instance
Driver_utils.creatBackupDrive(SettingActivity.this, google_api_client);
dialog.dismiss();
Toast.makeText(getApplicationContext(), R.string.backupss, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), R.string.inportfirest, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.nointe, Toast.LENGTH_LONG).show();
}
}
});
**And for Restore use this **
restore_from_drive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Launch user interface and allow user to select file
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"application/zip"})
.build(google_api_client);
try {
startIntentSenderForResult(
intentSender, REQ_CODE_OPEN, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, e.getMessage());
}
dialog.dismiss();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if (resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
if (!google_api_client.isConnecting() && !google_api_client.isConnected()) {
google_api_client.connect();
}
}
}
if (requestCode == REQ_CODE_OPEN && resultCode == RESULT_OK) {
DriveId mSelectedFileDriveId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("DriveID ---", mSelectedFileDriveId + "");
Gson gson = new Gson();
String json = gson.toJson(mSelectedFileDriveId); // myObject - instance of MyObject
editor_drive = preferences_driverId.edit();
editor_drive.putString("drive_id", json).commit();
Log.e(TAG, "driveId this 1-- " + mSelectedFileDriveId);
if (Utils.isInternetWorking()) {
//restore Drive file to SDCArd
Driver_utils.restoreDriveBackup(SettingActivity.this, google_api_client, GOOGLE_DRIVE_FILE_NAME, preferences_driverId, mfile);
Driver_utils.restore(SettingActivity.this);
} else {
Toast.makeText(getApplicationContext(), R.string.nointernets, Toast.LENGTH_LONG).show();
}
}
}
**Make a static Driver_utils class **
public class Driver_utils {
public static DriveFile mfile;
public static GoogleApiClient api;
public static DriveId driveId;
public static Context ctxs;
public static SharedPreferences preferences_driverId;
public static SharedPreferences.Editor editor;
private static final String GOOGLE_DRIVE_FILE_NAME = "Databackup";
public static void restoreDriveBackup(Context ctx, GoogleApiClient apis, String GOOGLE_DRIVE_FILE_NAME, SharedPreferences preferences_driverIds, DriveFile mfiles) {
mfile = mfiles;
api = apis;
preferences_driverId = preferences_driverIds;
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME))
.build();
Drive.DriveApi.query(api, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
Gson gson = new Gson();
String json = preferences_driverId.getString("drive_id", "");
DriveId driveId = gson.fromJson(json, DriveId.class);
Log.e("driveId put", "" + driveId);
Log.e("filesize in cloud ", +metadataBufferResult.getMetadataBuffer().get(0).getFileSize() + "");
metadataBufferResult.getMetadataBuffer().release();
mfile = Drive.DriveApi.getFile(api, driveId);
mfile.open(api, DriveFile.MODE_READ_ONLY, new DriveFile.DownloadProgressListener() {
#Override
public void onProgress(long bytesDown, long bytesExpected) {
Log.e("Downloading..", "" + bytesDown + "/" + bytesExpected);
}
})
.setResultCallback(restoreContentsCallback);
}
});
}
static final private ResultCallback<DriveApi.DriveContentsResult> restoreContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.e("Unable to open,try", "data");
return;
}
File sd = Environment.getExternalStorageDirectory();
String backupDBPath = "/Databackup.zip";
File imgFile = new File(sd, backupDBPath);
Log.e("FILE EXIST", imgFile.exists() + "");
if (!imgFile.exists())
try {
imgFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
imgFile = new File(imgFile.getAbsolutePath());
DriveContents contents = result.getDriveContents();
try {
FileOutputStream fos = new FileOutputStream(imgFile.getAbsolutePath());
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream in = new BufferedInputStream(contents.getInputStream());
byte[] buffer = new byte[1024];
int n, cnt = 0;
while ((n = in.read(buffer)) > 0) {
bos.write(buffer, 0, n);
cnt += n;
Log.e("buffer: ", buffer[0] + "");
Log.e("buffer: ", "" + buffer[1]);
Log.e("buffer: ", "" + buffer[2]);
Log.e("buffer: ", "" + buffer[3]);
bos.flush();
}
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Unzip when download from drive
try {
String dest_file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup";
String src_location = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup.zip";
Decompress.unzip(new File(src_location), new File(dest_file_path));
} catch (Exception e) {
e.printStackTrace();
}
}
};
public static void creatBackupDrive(Context ctx, GoogleApiClient apis) {
ctxs = ctx;
api = apis;
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
final public static ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.e(TAG, "Error while trying to create new file contents");
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
.setMimeType("application/zip")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final public static ResultCallback<DriveFolder.DriveFileResult> fileCallback = new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
preferences_driverId = ctxs.getSharedPreferences("ID", MODE_PRIVATE);
editor = preferences_driverId.edit();
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
driveId = result.getDriveFile().getDriveId();
Log.e(TAG, "Created a file with content: " + driveId);
Gson gson = new Gson();
String json = gson.toJson(driveId); // myObject - instance of MyObject
editor.putString("drive_id", json).commit();
Log.e(TAG, "driveId " + driveId);
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, new DriveFile.DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
Log.e(TAG, "Creating backup file" + bytesDownloaded + "/" + bytesExpected);
}
}).setResultCallback(contentsOpenedCallback);
}
};
final public static ResultCallback<DriveApi.DriveContentsResult> contentsOpenedCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error opening file");
return;
}
String sd = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DiaryDatabackup.zip";
Log.e("DB FILE NAME---", sd + "");
DriveContents contents = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(contents.getOutputStream());
byte[] buffer = new byte[1024];
int n;
try {
FileInputStream is = new FileInputStream(sd);
BufferedInputStream in = new BufferedInputStream(is);
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
Log.e("Backing up...", "Backup");
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
contents.commit(api, null).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Log.e("Backup completed!", "complete"+status);
}
});
}
};
public static void trash(DriveId dId, GoogleApiClient apis) {
api = apis;
try {
Log.e(TAG,"Goes in trans" );
DriveFile sumFile = dId.asDriveFile();
com.google.android.gms.common.api.Status deleteStatus =
sumFile.delete(api).await();
if (!deleteStatus.isSuccess()) {
Log.e(TAG, "Unable to delete app data.");
} else {
// Remove stored DriveId.
preferences_driverId.edit().remove("drive_id").apply();
}
Log.d(TAG, "Past sums deleted.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void restore(Context ctx) {
OutputStream myOutput;
String dbpath = "//data//" + ctx.getPackageName() + "//databases//databaseName.db";
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup";
File directorys = new File(sdpath + "/backup_sd");
if (directorys.exists()) {
try {
myOutput = new FileOutputStream(Environment.getDataDirectory()
+ dbpath);
// Set the folder on the SDcard
File directory = new File(sdpath + "/backup_sd");
// Set the input file stream up:
InputStream myInputs = new FileInputStream(directory.getPath());
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInputs.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInputs.close();
Toast.makeText(ctx, R.string.successss, Toast.LENGTH_LONG)
.show();
} catch (FileNotFoundException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("NO DB YET ", "Created");
Toast.makeText(ctx, R.string.savesome, Toast.LENGTH_LONG).show();
}
}
public static void create_backup(Context ctx) {
InputStream myInput;
String dbpath = "//data//" + ctx.getPackageName() + "//databases//databaseName.db";
String sdpath_createbackup = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup";
File file = new File(sdpath_createbackup);
if (!file.exists())
file.mkdirs();
try {
myInput = new FileInputStream(Environment.getDataDirectory()
+ dbpath);
// Set the output folder on the Scard
File directory = new File(file + "/backup_sd");
// Create the folder if it doesn't exist:
if (!directory.exists()) {
directory.createNewFile();
}
// Set the output file stream up:
OutputStream myOutput = new FileOutputStream(directory.getPath());
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[100024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(ctx, R.string.backups, Toast.LENGTH_LONG)
.show();
} catch (FileNotFoundException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
Log.e("error", e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
Log.e("error 1", e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
String src_file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup";
String destination_location = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup.zip";
Decompress.backupfolder(new File(src_file_path), new File(destination_location));
}
}
And You Need Decomposer file just create and Copy this
public class Decompress {
public static boolean unzip(File zipfile, File directory) {
BufferedReader br = null;
try {
ZipFile zfile = new ZipFile(zipfile);
Enumeration<? extends ZipEntry> entries = zfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
InputStream in = zfile.getInputStream(entry);
copy(in, file);
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return true;
}
public static boolean backupfolder(File directory, File zipfile) {
try {
URI base = directory.toURI();
Deque<File> queue = new LinkedList<>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = out;
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty()) {
directory = queue.pop();
for (File kid : directory.listFiles()) {
String name = base.relativize(kid.toURI()).getPath();
if (kid.isDirectory()) {
queue.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
} else {
zout.putNextEntry(new ZipEntry(name));
copy(kid, zout);
zout.closeEntry();
}
}
}
res.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
copy(in, out);
} finally {
in.close();
}
}
private static void copy(InputStream in, File file) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
copy(in, out);
} finally {
out.close();
}
}
}
My answer assumes that you have a keystore file to sign your app with. If you don't, this link shows you how.
The next thing you need to do is to download the Android and Google play Services SDKs and get an Android certificate, as described here
Now your app should be able to access the Google Drive APIs.
In your activity, create these variables
/**
* Handle access to Drive resources/files.
*/
DriveResourceClient mDriveResourceClient;
/**
* Base folder. This is where the backup will be created
*/
DriveFolder baseFolder;
/**
* Request code for google sign-in, to be used for result of Drive sign-in
* Can be any suitable value
*/
protected static final int REQUEST_CODE_SIGN_IN = 0;
/**
* String variables to hold file names, file paths etc.
*/
static final String BACK_UP = <NAME OF BACKUP FILE CREATED ON DRIVE> ;
static final String dbPath = <PATH TO YOUR DATABASE>;
static final String DATABASE_NAME = <NAME OF YOUR DATABASE>;
/*
* This text view is used to show the output from various operations
*/
private TextView tvDriveResult;
When the user starts the backup process call the function singIn()
/**
* Starts the sign-in process and initializes the Drive client.
*/
private void singIn() {
Set<Scope> requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
}
The singIn() function will handle a user sign - in by starting Google Sign in Client. You will need to handle the result of this client. Use the following code.
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode != RESULT_OK) {
/* Sign-in may fail or be cancelled by the user. For this sample, sign-in is
* required and is fatal. For apps where sign-in is optional, handle appropriately
*/
Log.e(TAG, "Sign-in failed.");
return;
}
Task<GoogleSignInAccount> getAccountTask =
GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
} else {
Log.e(TAG, "Sign-in failed.");
tvDriveResult.append("Sign-in failed\n");
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
After sign-in has been successfully completed, the drive client is initialised above by calling the initializeDriveClient(GoogleSignInAccount signInAccount) function.
/**
* Continues the sign-in process, initializing the Drive clients with the current
* user's account.
*/
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
onDriveClientReady();
}
After the drive client is set up, onDriveClientReady() is called. This function proceeds to create / restore your back-up. The functionality here is very simple a. Get the base folder of the user's Google Drive account. b. Check if a back-up file exists. c. If yes, copy that backup to the local database file (over write complete file). d. If no, copy the local database file to the user's Google Drive base folder. You can add some finesse to this logic if you wish. My code is to help you understand the process.
/**
* Called after the user has signed in and the Drive client has been initialized.
*/
private void onDriveClientReady(){
/* Initialise the root folder. */
/* Since the tasks are executed in a separate execution threads, the remaining tasks are called from within each other */
getRootFolder();
}
The getRootFolder() function proceeds as follows
private void getRootFolder() {
/* Get the app folder */
Task<DriveFolder> appFolderTask = mDriveResourceClient.getRootFolder();
appFolderTask
.addOnSuccessListener(this, new OnSuccessListener<DriveFolder>() {
#Override
public void onSuccess(DriveFolder driveFolder) {
tvDriveResult.append("Root folder found\n");
baseFolder = driveFolder;
/* Base folder is found, now check if backup file exists */
checkForBackUp();
/* Use this to delete files. Remember to comment out the line able it */
/* listFilesInBaseFolder(); */
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Root folder not found, error: " + e.toString() + "\n");
}
});
}
There is also a function in here called listFilesInBaseFolder() to delete (permanently delete not simply trash) all files you created. It has been commented out in. Use it in case you want to delete files you created, use with caution. As far as I can tell it works only on files that were created by your application.
Check for backup.
private void checkForBackUp() {
/* Build a query */
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, BACK_UP))
.build();
/* Query contents of app folder */
Task<MetadataBuffer> queryTask = mDriveResourceClient.queryChildren(baseFolder, query);
/* Check for result of query */
queryTask
.addOnSuccessListener(this, new OnSuccessListener<MetadataBuffer>() {
#Override
public void onSuccess(MetadataBuffer metadataBuffer) {
/* if count is 0, the file doesn't exist */
if (metadataBuffer.getCount() == 0){
tvDriveResult.append("File " + BACK_UP + " not found\n");
/* Make file backup */
backUpDatabase();
} else {
tvDriveResult.append(metadataBuffer.getCount() + " Instances of file " + BACK_UP + " found\n");
Metadata metadata = metadataBuffer.get(0);
restoreBackUp(metadata.getDriveId().asDriveFile());
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not search for file, error: " + e.toString() + "\n");
}
});
}
restoreBackUp(DriveFile driveFile) will over write the local database file with the file found on Goole Drive.
private void restoreBackUp(DriveFile driveFile) {
tvDriveResult.append("Restoring from backup\n");
/* Get the path of the local backup */
File dbFileOld = new File(dbPath + DATABASE_NAME);
/* Check of dbFileExists on device, delete if it does because it needs to be completely over written */
if (dbFileOld.exists()){
dbFileOld.delete();
}
File dbFileNew = new File(dbPath + DATABASE_NAME);
/* File input stream from database to read from */
final FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(dbFileNew);
} catch (FileNotFoundException e) {
tvDriveResult.append("Could not get input stream from local file\n");
return;
}
/* Task to open file */
Task<DriveContents> openFileTask =
mDriveResourceClient.openFile(driveFile, DriveFile.MODE_READ_ONLY);
/* Continue with task */
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>(){
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents backupContents = task.getResult();
InputStream inputStream = backupContents.getInputStream();
tvDriveResult.append("Attempting to restore from database\n");
byte[] buffer = new byte[4096];
int c;
while ((c = inputStream.read(buffer, 0, buffer.length)) > 0){
fileOutputStream.write(buffer, 0, c);
}
fileOutputStream.flush();
fileOutputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
tvDriveResult.append("Database restored\n");
/* Return statement needed to avoid task failure */
Task<Void> discardTask = mDriveResourceClient.discardContents(backupContents);
return discardTask;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not read file contents\n");
}
});
}
And lastly, backUpDatabase() creates a backup of your local database.
private void backUpDatabase() {
tvDriveResult.append("Creating Drive back-up");
/* get the path of the local backup */
File dbFile = new File(dbPath + DATABASE_NAME);
/* Check of dbFileExists on device */
if (! dbFile.exists()){
tvDriveResult.append("Local database not found?!\n");
return;
}
/* File input stream from database to read from */
final FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(dbFile);
} catch (FileNotFoundException e) {
tvDriveResult.append("Could not get input stream from local file\n");
return;
}
/* Task to make file */
final Task<DriveContents> createContentsTask = mDriveResourceClient.createContents();
tvDriveResult.append("Creating a back-up of the Database File\n");
Tasks.whenAll(createContentsTask).continueWithTask(new Continuation<Void, Task<DriveFile>>() {
#Override
public Task<DriveFile> then(#NonNull Task<Void> task) throws Exception {
/* Retrieved the drive contents returned by the Task */
DriveContents contents = createContentsTask.getResult();
/* Output stream where data will be written */
OutputStream outputStream = contents.getOutputStream();
/* File output stream */
tvDriveResult.append("Attempting to write\n");
byte[] buffer = new byte[4096];
int c;
while ((c = fileInputStream.read(buffer, 0, buffer.length)) > 0){
outputStream.write(buffer, 0, c);
}
outputStream.flush();
outputStream.close();
fileInputStream.close();
tvDriveResult.append("Database written\n");
/* Save the file, using MetadataChangeSet */
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(BACK_UP)
.setMimeType("application/x-sqlite3")
.setStarred(false)
.build();
return mDriveResourceClient.createFile(baseFolder, changeSet, contents);
}
})
/* Task successful */
.addOnSuccessListener(new OnSuccessListener<DriveFile>() {
#Override
public void onSuccess(DriveFile driveFile) {
tvDriveResult.append("Back up file created\n");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not create back up file\n");
}
});
}
And that is it! This should get you started with basic operations. I recommend going through Google's Developer Guide for a deeper dive.
My goal is to create Java application which would be server, and Android(client) socket connection, and make Android phone listen to my commands send from a server. My question is, how should i make my Android phone always listen for incoming commands(Strings) pushed from Java application. What is a best choice ? Thread, Service ?
Here is my code : Server in java:
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
Android Client code:
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
DataOutputStream os;
public final String TAG = "CLIENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
ConnectThread thread = new ConnectThread();
thread.execute();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ConnectThread extends AsyncTask<String, String, String> {
public ConnectThread() {
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.i(TAG,"Do in background");
return connect();
}
public String connect() {
try {
Log.i(TAG," creating socket");
socket = new Socket("192.168.1.10", 9000);
Log.i(TAG," socket created");
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
Log.i(TAG," Streams are set");
Log.i(TAG,"::"+is.readUTF().toString());
text.setText(is.readLine().toString());
return is.readLine().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
Log.d("fail", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("fail", e.toString());
}
return "nothing";
}
}
}
I have solved my problem. Im sending messages from my java server to android trough a socket, and android is always listening. Here is my code:
Java :
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeUTF("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
And android :
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
ObjectOutputStream os;
public final String TAG = "CLIENT";
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
handler = new Handler();
Thread x = new Thread(new ClientThread());
x.start();
handler = new Handler();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//
public class ClientThread implements Runnable {
public ClientThread() {
// TODO Auto-generated constructor stub
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String line = null;
while ((line = in.readUTF()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
}
}
outStream.write(msgBuffer);
It writes only first bit. how to write 8 bit out of it.If we are sending 00000001 means it writes only 0. But we want to write whole 8 bit how to achieve it.
public class MainActivity extends ActionBarActivity {
private ToggleButton power, simulation, reset, pause, replay, diagnose,
abs, emergency;
private static final String TAG = "bluetooth1";
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:12:02:28:75:34";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
power = (ToggleButton) findViewById(R.id.toggleButton1);
simulation = (ToggleButton) findViewById(R.id.simulation_tb);
reset = (ToggleButton) findViewById(R.id.reset_bt);
pause = (ToggleButton) findViewById(R.id.pause_bt);
replay = (ToggleButton) findViewById(R.id.replay_bt);
diagnose = (ToggleButton) findViewById(R.id.diagnose_bt);
abs = (ToggleButton) findViewById(R.id.abs_bt);
emergency = (ToggleButton) findViewById(R.id.emergency_bt);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
power.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (power.isChecked()) {
String str = "1";
int i = Integer.parseInt(str);
String binarystr = Integer.toBinaryString(i);
char[] buffer = new char[binarystr.length()];
binarystr.getChars(0, binarystr.length(), buffer, 0);
System.out.println("char array:: "
+ Arrays.toString(buffer));
byte[] binaryFormat = getbyteFromString(buffer);
for (byte b : binaryFormat) {
sendData(Integer.toBinaryString(b & 255 | 256)
.substring(1));
}
Toast.makeText(getApplicationContext(), "LED ON",
Toast.LENGTH_LONG).show();
} else {
sendData("0");
Toast.makeText(getApplicationContext(), "LED OFF",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.const_closeApp))
.setPositiveButton(getString(R.string.const_yes),
dialogClickListener)
.setNegativeButton(getString(R.string.const_no),
dialogClickListener).show();
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(new
// BTStateChangedBroadcastReceiver());
System.exit(0);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if (Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#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;
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
Log.d(TAG, "...This is the value byte: " + msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static byte[] getbyteFromString(char[] binarystr) {
int length = binarystr.length / 8;
if (binarystr.length % 8 > 0)
length++;
int iterationCount = length;
byte[] binaryFormat = new byte[iterationCount];
int iter = iterationCount - 1;
for (int i = binarystr.length - 1; i >= 0;) {
byte byt = 0x0;
for (int j = 0; j < 8; j++) {
if (i < 0)
break;
int b = binarystr[i] - 48;
byt = (byte) (byt + (b << j));
i--;
}
binaryFormat[iter] = byt;
iter--;
}
return binaryFormat;
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.getMessage() + ".");
}
/*
* try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); }
* catch (IOException e) { errorExit("Fatal Error",
* "In onResume() and socket create failed: " + e.getMessage() + "."); }
*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error",
"In onResume() and unable to close socket during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onResume() and output stream creation failed:"
+ e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
}
It looks like your code is not complete. Anyway, I suggest to use the DataInputStream / DataOutputStream of Android. Just wrap your streams into them. They provide methods for writing any kind of primitive datatype up to String with arbitrary encoding. All you need to do is use the writeString(...) method and use the read String method on the other side. This way you don't need to convert the String in order to write it into you stream and you don't need to care about how to reconstruct it from the stream.
If you only want to write Strings you can use the BufferedWriter which allows you to only write Strings to an stream, you can use it like this to stick it onto a 'OutputStream'
OutputStreamWriter osw = new OutputStreamWriter(outStream);
BufferedWriter writer = new BufferedWriter(osw);
I wrote a code which takes picture from android device and then upload it on server.Can also upload pic from gallery. Uploading from gallery works perfectly.It is able to intent to mobile camera when clicked on capture button but when i return i didn't got any image and when i checked the gallery no image was captured.
Got menifest permission also
android.permission.WRITE_EXTERNAL_STORAGE"
android.permission.READ_EXTERNAL_STORAGE"
android.permission.CAMERA"
This is code in my Fragments onCreateView() class:
mTakePhoto = (Button) rootView.findViewById(R.id.take_photo);
mselectPhoto = (Button) rootView.findViewById(R.id.select_photo);
mImageView = (ImageView) rootView.findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
TAKE_PICTURE);
}
});
mselectPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,
IMAGE_PICKER_SELECT);
}
});
In the above code i think intents works perfectly
In bellow code, the (requestCode == IMAGE_PICKER_SELECT) condition works perfectly. But it seems like i didn't get any data when i took PICTURE
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICKER_SELECT
&& resultCode == Activity.RESULT_OK) {
Bitmap bitmap = getBitmapFromCameraData(data, getActivity());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(bitmap);
}
if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK
&& data != null) {
// get bundle
Bundle extras = data.getExtras();
// get bitmap
cameraBitmap = (Bitmap) extras.get("data");
int nh = (int) (cameraBitmap.getHeight() * (512.0 / cameraBitmap
.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(cameraBitmap, 512, nh,
true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(cameraBitmap);
// setPic();
}
}
I m also giving the Code of my Multipartentity class
public class MultipartEntity implements HttpEntity {
enter code here
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
I m stuck for almost the fullday. Help!!
Open your camera with below code and check with it:
private Uri mImageCaptureUri;
mImageCaptureUri = Uri.parse("content://YOUR PACKAGE NAME/");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent,TAKE_PICTURE);
I created a method to call whn button is clicked
mTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
takePhoto();
}
});
method to intent and getTempFile() to keel temporary file..
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getActivity())) );
startActivityForResult(intent, TAKE_PICTURE);
}
private File getTempFile(Context context){
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
this link help me
http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html
Please check the code below.
I am not able to copy a resource file to external storage in android phone.
Though, i'm able to copy using the code i've commented but I want to know the problem with my original code.
public class ExternalData extends Activity implements OnItemSelectedListener,
OnClickListener {
TextView canRead = null;
TextView canWrite = null;
String state = null;
boolean canR, canW;
EditText userEnteredFileName;
Button bConfirm, bSaveAs;
Spinner spinner = null;
String[] stuff = { "Music", "Pictures", "Downloads" };
File path = null;
File file = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.externaldata);
canRead = (TextView) findViewById(R.id.tvCanRead);
canWrite = (TextView) findViewById(R.id.tvCanWrite);
userEnteredFileName = (EditText) findViewById(R.id.etUserEnteredFileName);
bConfirm = (Button) findViewById(R.id.bConfirm);
bSaveAs = (Button) findViewById(R.id.bSaveAs);
bConfirm.setOnClickListener(this);
bSaveAs.setOnClickListener(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, stuff);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
break;
case 1:
path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
break;
case 2:
path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
break;
}
}
public void checkState() {
state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
canRead.setText("Can Read: true");
canWrite.setText("Can Write: true");
canR = canW = true;
} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
canRead.setText("Can Read: true");
canWrite.setText("Can Write: false");
canR = true;
canW = false;
} else {
canRead.setText("Can Read: false");
canWrite.setText("Can Write: false");
canR = canW = false;
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.bConfirm:
bSaveAs.setVisibility(View.VISIBLE);
break;
case R.id.bSaveAs:
checkState();
if(canR == canW == true){
file = new File (path, userEnteredFileName.getText().toString() + "/");
try {
if(!file.exists()){
boolean success = file.mkdirs();
if(success){
Toast.makeText(ExternalData.this, "File created", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ExternalData.this, "Not able to create file", Toast.LENGTH_LONG).show();
}
}
InputStream fis = getResources().openRawResource(R.drawable.darthvader);
/* this works....but wats wrong with the original code
file = new File(file, "darthVader.png");
if(!file.exists()){
file.createNewFile();
}
*/
FileOutputStream fos = new FileOutputStream(file);
byte[] data = new byte[fis.available()];
fis.read(data);
fos.write(data);
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(ExternalData.this, "FilNOT", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(ExternalData.this, "IO", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Did you request the permission in your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
see this example for How to write file in sdcard (external storage)
InputStream input;
try {
URL url = new URL (strURL);
input = url.openStream();
byte[] buffer = new byte[1500];
OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
{
output.write(buffer, 0, bytesRead);
}
finally
{
output.close();
buffer=null;
}
don't forget to give permisson in manifeast file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />