I'm trying to make an app in Android Studio which requires you to download a file to the sdcard/Download/ folder on the users device. The problem is that when I enter the URL to download from and click Download, the app says "Unfortunately, * has stopped". I have quite a few files so here they are.
First, heres the Manifest...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.NautGames.xecta.app" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.NautGames.xecta.app.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>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission: Writing to SDCard -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</manifest>
Heres the MainActivity class...
package com.NautGames.xecta.app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//Chat bot library
import org.alicebot.ab.Chat;
import org.alicebot.ab.Bot;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//EditText mEdit = (EditText)findViewById(R.id.editText1);
public void buttonOnClick(View v)
{
input = (TextView) findViewById(R.id.editText1);
String dbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Ab";
Button button=(Button) v;
//Creating bot
String botname="xecta";
String path= dbPath;
Bot xecta = new Bot(botname, path);
Chat chatSession = new Chat(xecta);
String request = input.getText().toString();
String response = chatSession.multisentenceRespond(request);
((Button) v).setText(response);
}
public void buttonDownload(View v)
{
}
#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);
}
}
DownloaderThread (to download file)...
package com.NautGames.xecta.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.Environment;
import android.os.Message;
/**
* Downloads a file in a thread. Will send messages to the
* AndroidFileDownloader activity to update the progress bar.
*/
public class DownloaderThread extends Thread
{
// constants
private static final int DOWNLOAD_BUFFER_SIZE = 4096;
// instance variables
private AndroidFileDownloader parentActivity;
private String downloadUrl;
/**
//Instantiates a new DownloaderThread object.
// #param parentActivity Reference to AndroidFileDownloader activity.
// #param inUrl String representing the URL of the file to be downloaded.
*/
public DownloaderThread(AndroidFileDownloader inParentActivity, String inUrl)
{
downloadUrl = "";
if(inUrl != null)
{
downloadUrl = inUrl;
}
parentActivity = inParentActivity;
}
/**
* Connects to the URL of the file, begins the download, and notifies the
* AndroidFileDownloader activity of changes in state. Writes the file to
* the root of the SD card.
*/
#Override
public void run()
{
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
Message msg;
// we're going to connect now
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_CONNECTING_STARTED,
0, 0, downloadUrl);
parentActivity.activityHandler.sendMessage(msg);
try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileSize = conn.getContentLength();
// get the filename
lastSlash = url.toString().lastIndexOf('/');
fileName = "file.bin";
if(lastSlash >=0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if(fileName.equals(""))
{
fileName = "file.bin";
}
// notify download start
int fileSizeInKB = fileSize / 1024;
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_DOWNLOAD_STARTED,
fileSizeInKB, 0, fileName);
parentActivity.activityHandler.sendMessage(msg);
// start download
inStream = new BufferedInputStream(conn.getInputStream());
outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
outStream.write(data, 0, bytesRead);
// update progress bar
totalRead += bytesRead;
int totalReadInKB = totalRead / 1024;
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR,
totalReadInKB, 0);
parentActivity.activityHandler.sendMessage(msg);
}
outStream.close();
fileStream.close();
inStream.close();
if(isInterrupted())
{
// the download was canceled, so let's delete the partially downloaded file
outFile.delete();
}
else
{
// notify completion
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_DOWNLOAD_COMPLETE);
parentActivity.activityHandler.sendMessage(msg);
}
}
catch(MalformedURLException e)
{
String errMsg = parentActivity.getString(R.string.error_message_bad_url);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
catch(FileNotFoundException e)
{
String errMsg = parentActivity.getString(R.string.error_message_file_not_found);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
catch(Exception e)
{
String errMsg = parentActivity.getString(R.string.error_message_general);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
}
}
And lastly, The AndroidFileDownload(also to download file)...
package com.NautGames.xecta.app;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AndroidFileDownloader extends Activity implements OnClickListener
{
// Used to communicate state changes in the DownloaderThread
public static final int MESSAGE_DOWNLOAD_STARTED = 1000;
public static final int MESSAGE_DOWNLOAD_COMPLETE = 1001;
public static final int MESSAGE_UPDATE_PROGRESS_BAR = 1002;
public static final int MESSAGE_DOWNLOAD_CANCELED = 1003;
public static final int MESSAGE_CONNECTING_STARTED = 1004;
public static final int MESSAGE_ENCOUNTERED_ERROR = 1005;
// instance variables
private AndroidFileDownloader thisActivity;
private Thread downloaderThread;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
thisActivity = this;
downloaderThread = null;
progressDialog = null;
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.download_button);
button.setOnClickListener(this);
}
/** Called when the user clicks on something. */
#Override
public void onClick(View view)
{
EditText urlInputField = (EditText) this.findViewById(R.id.url_input);
String urlInput = urlInputField.getText().toString();
downloaderThread = new DownloaderThread(thisActivity, urlInput);
downloaderThread.start();
}
/**
* This is the Handler for this activity. It will receive messages from the
* DownloaderThread and make the necessary updates to the UI.
*/
public Handler activityHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch(msg.what)
{
/*
* Handling MESSAGE_UPDATE_PROGRESS_BAR:
* 1. Get the current progress, as indicated in the arg1 field
* of the Message.
* 2. Update the progress bar.
*/
case MESSAGE_UPDATE_PROGRESS_BAR:
if(progressDialog != null)
{
int currentProgress = msg.arg1;
progressDialog.setProgress(currentProgress);
}
break;
/*
* Handling MESSAGE_CONNECTING_STARTED:
* 1. Get the URL of the file being downloaded. This is stored
* in the obj field of the Message.
* 2. Create an indeterminate progress bar.
* 3. Set the message that should be sent if user cancels.
* 4. Show the progress bar.
*/
case MESSAGE_CONNECTING_STARTED:
if(msg.obj != null && msg.obj instanceof String)
{
String url = (String) msg.obj;
// truncate the url
if(url.length() > 16)
{
String tUrl = url.substring(0, 15);
tUrl += "...";
url = tUrl;
}
String pdTitle = thisActivity.getString(R.string.progress_dialog_title_connecting);
String pdMsg = thisActivity.getString(R.string.progress_dialog_message_prefix_connecting);
pdMsg += " " + url;
dismissCurrentProgressDialog();
progressDialog = new ProgressDialog(thisActivity);
progressDialog.setTitle(pdTitle);
progressDialog.setMessage(pdMsg);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
// set the message to be sent when this dialog is canceled
Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
progressDialog.setCancelMessage(newMsg);
progressDialog.show();
}
break;
/*
* Handling MESSAGE_DOWNLOAD_STARTED:
* 1. Create a progress bar with specified max value and current
* value 0; assign it to progressDialog. The arg1 field will
* contain the max value.
* 2. Set the title and text for the progress bar. The obj
* field of the Message will contain a String that
* represents the name of the file being downloaded.
* 3. Set the message that should be sent if dialog is canceled.
* 4. Make the progress bar visible.
*/
case MESSAGE_DOWNLOAD_STARTED:
// obj will contain a String representing the file name
if(msg.obj != null && msg.obj instanceof String)
{
int maxValue = msg.arg1;
String fileName = (String) msg.obj;
String pdTitle = thisActivity.getString(R.string.progress_dialog_title_downloading);
String pdMsg = thisActivity.getString(R.string.progress_dialog_message_prefix_downloading);
pdMsg += " " + fileName;
dismissCurrentProgressDialog();
progressDialog = new ProgressDialog(thisActivity);
progressDialog.setTitle(pdTitle);
progressDialog.setMessage(pdMsg);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.setMax(maxValue);
// set the message to be sent when this dialog is canceled
Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
progressDialog.setCancelMessage(newMsg);
progressDialog.setCancelable(true);
progressDialog.show();
}
break;
/*
* Handling MESSAGE_DOWNLOAD_COMPLETE:
* 1. Remove the progress bar from the screen.
* 2. Display Toast that says download is complete.
*/
case MESSAGE_DOWNLOAD_COMPLETE:
dismissCurrentProgressDialog();
displayMessage(getString(R.string.user_message_download_complete));
break;
/*
* Handling MESSAGE_DOWNLOAD_CANCELLED:
* 1. Interrupt the downloader thread.
* 2. Remove the progress bar from the screen.
* 3. Display Toast that says download is complete.
*/
case MESSAGE_DOWNLOAD_CANCELED:
if(downloaderThread != null)
{
downloaderThread.interrupt();
}
dismissCurrentProgressDialog();
displayMessage(getString(R.string.user_message_download_canceled));
break;
/*
* Handling MESSAGE_ENCOUNTERED_ERROR:
* 1. Check the obj field of the message for the actual error
* message that will be displayed to the user.
* 2. Remove any progress bars from the screen.
* 3. Display a Toast with the error message.
*/
case MESSAGE_ENCOUNTERED_ERROR:
// obj will contain a string representing the error message
if(msg.obj != null && msg.obj instanceof String)
{
String errorMessage = (String) msg.obj;
dismissCurrentProgressDialog();
displayMessage(errorMessage);
}
break;
default:
// nothing to do here
break;
}
}
};
/**
* If there is a progress dialog, dismiss it and set progressDialog to
* null.
*/
public void dismissCurrentProgressDialog()
{
if(progressDialog != null)
{
progressDialog.hide();
progressDialog.dismiss();
progressDialog = null;
}
}
/**
* Displays a message to the user, in the form of a Toast.
* #param message Message to be displayed.
*/
public void displayMessage(String message)
{
if(message != null)
{
Toast.makeText(thisActivity, message, Toast.LENGTH_SHORT).show();
}
}
}
And heres the Log:
Process: com.NautGames.xecta.app, PID: 3032
java.lang.IllegalStateException: Could not find a method onClick(View) in the activity class com.NautGames.xecta.app.MainActivity for onClick handler on view class android.widget.Button with id 'download_button'
at android.view.View$1.onClick(View.java:3810)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.om.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: onClick [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:857)
at android.view.View$1.onClick(View.java:3803)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Could anyone tell me what the problem is?
Thanks in advance.
Since you said it's in AndroidFileDownload, I'd suggest you to do as follows:
#Override
public void onClick(View view)
// you need to get the id of the clicked view:
if(view.getId() == R.id.download_button) {
EditText urlInputField = (EditText) thisActivity.findViewById(R.id.url_input);
String urlInput = urlInputField.getText().toString();
downloaderThread = new DownloaderThread(thisActivity, urlInput);
downloaderThread.start();
}
}
This is the cause of: NoSuchMethodException: onClick [class android.view.View]. It means that your onClick method cannot find your button (id) where you did set an onClickListener method.
And then, in the future, I think the problem will be that AndroidFileDownload is not declared in your Manifest file. You should add it as follows:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.NautGames.xecta.app.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>
// add every activity in your app like this below
<activity
android:name="com.NautGames.xecta.app.AndroidFileDownloader"
android:label="#string/app_name" />
</application>
Related
I am currently developing my first app that able to switch activity tab (Android's Fragment). I have 4 tabs, in one of the tabs, I have implemented an image recognition for character recognition (OCR). I used simplified OCR Tesseract library which is called Easy OCR Library made by Priyank Verma. I have tested the example from that library and it works. But when I use the library for my own app, it doesn't work properly.
Let me explain, in one of my app's tab, I have a 'Scan' button that utilizes use my phone camera to take a picture. After the picture have been taken, my app should scan the captured image in the saved directory for character recognition. Next, my app will return to the previous 'Scan' tab and then will display the output of the character recognition above the 'Scan' button in that tab. And that just it, my app doesn't seem to scan. The real problem is that after the picture have been taken & saved, my app returns back to the tab with no output at all. My code should work but sadly it doesn't. No error, no nothing and I am losing my mind for days to figure out what is wrong.
Here's the code:-
---------- My App's Manifest ----------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kaydarinapp.queueappv2">
<!-- Save file permission -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- Read file permission -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Camera permission -->
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<!-- Internet permission -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
---------- From My App's Tab ----------
My Tab's XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Tab2"
android:gravity="center_horizontal"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_marginTop="45dp"
android:layout_gravity="center_horizontal"
android:textSize="8pt"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_marginTop="20dp"
android:text="Scan"
android:layout_gravity="center_vertical" />
</LinearLayout>
My Tab Java
package com.kaydarinapp.queueappv2;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wordpress.priyankvex.easyocrscannerdemo.Config;
import com.wordpress.priyankvex.easyocrscannerdemo.EasyOcrScanner;
import com.wordpress.priyankvex.easyocrscannerdemo.EasyOcrScannerListener;
/**
* Created by Kaydarin on 6/1/2016.
*/
//Our class extending fragment
public class Tab2 extends Fragment implements EasyOcrScannerListener {
private LinearLayout linearLayout;
private FragmentActivity fragActivity;
EasyOcrScanner mEasyOcrScanner;
TextView textView;
ProgressDialog mProgressDialog;
Button btnCapture;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
fragActivity = super.getActivity();
linearLayout = (LinearLayout) inflater.inflate(R.layout.tab2, container, false);
textView = (TextView) fragActivity.findViewById(R.id.textView);
// initialize EasyOcrScanner instance.
mEasyOcrScanner = new EasyOcrScanner(getActivity(), "EasyOcrScanner",
Config.REQUEST_CODE_CAPTURE_IMAGE, "eng");
// Set ocrScannerListener
mEasyOcrScanner.setOcrScannerListener(this);
btnCapture = (Button) linearLayout.findViewById(R.id.button);
btnCapture.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mEasyOcrScanner.takePicture();
}
});
return linearLayout;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Call onImageTaken() in onActivityResult.
if (resultCode == getActivity().RESULT_OK && requestCode == Config.REQUEST_CODE_CAPTURE_IMAGE){
mEasyOcrScanner.onImageTaken();
}
}
/**
* Callback when after taking picture, scanning process starts.
* Good place to show a progress dialog.
* #param filePath file path of the image file being processed.
*/
#Override
public void onOcrScanStarted(String filePath) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Scanning...");
mProgressDialog.show();
}
/**
* Callback when scanning is finished.
* Good place to hide teh progress dialog.
* #param bitmap Bitmap of image that was scanned.
* #param recognizedText Scanned text.
*/
#Override
public void onOcrScanFinished(Bitmap bitmap, String recognizedText) {
textView.setText(recognizedText);
if (mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
}
---------- From Easy OCR Library ----------
Easy OCR Library's Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wordpress.priyankvex.easyocrscanner">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
</manifest>
Config Java
package com.wordpress.priyankvex.easyocrscannerdemo;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*/
public class Config {
public static String TAG = "OcrScanner";
public static int REQUEST_CODE_CAPTURE_IMAGE = 1995;
}
EasyOCRScannerListener Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.graphics.Bitmap;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*
* Interface for the callbacks for {#link EasyOcrScanner}.
*/
public interface EasyOcrScannerListener {
public void onOcrScanStarted(String filePath);
public void onOcrScanFinished(Bitmap bitmap, String recognizedText);
}
EasyOCRScanner Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import java.io.File;
import java.util.Calendar;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*
* Class to handle scanning of image.
*/
public class EasyOcrScanner {
protected Activity mActivity;
private String directoryPathOriginal;
private String filePathOriginal;
private int requestCode;
private EasyOcrScannerListener mOcrScannerListener;
private String trainedDataCode;
public EasyOcrScanner(Activity activity, String directoryPath, int requestCode, String trainedDataCode){
this.mActivity = activity;
this.directoryPathOriginal = directoryPath;
this.requestCode = requestCode;
this.trainedDataCode = trainedDataCode;
}
public void takePicture(){
Intent e = new Intent("android.media.action.IMAGE_CAPTURE");
this.filePathOriginal = FileUtils.getDirectory(this.directoryPathOriginal) + File.separator + Calendar.getInstance().getTimeInMillis() + ".jpg";
e.putExtra("output", Uri.fromFile(new File(this.filePathOriginal)));
startActivity(e);
}
public void onImageTaken(){
Log.d(Config.TAG, "onImageTaken with path " + this.filePathOriginal);
ImageProcessingThread thread = new ImageProcessingThread(this.mOcrScannerListener,
this.filePathOriginal, this.directoryPathOriginal, this.mActivity, this.trainedDataCode);
thread.execute();
}
private void startActivity(Intent intent){
if(this.mActivity != null) {
this.mActivity.startActivityForResult(intent, this.requestCode);
}
}
public void setOcrScannerListener(EasyOcrScannerListener mOcrScannerListener) {
this.mOcrScannerListener = mOcrScannerListener;
}
}
FileUtils Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.os.Environment;
import android.util.Log;
import java.io.File;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*/
public class FileUtils {
public static String getDirectory(String folderName) {
File directory = null;
directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + folderName);
if(!directory.exists()) {
directory.mkdirs();
}
return directory.getAbsolutePath();
}
public static String getTessdataDirectory(String directoryPath){
File tessdataDirectory = new File(directoryPath + "/tessdata");
if (tessdataDirectory.mkdirs()){
Log.d(Config.TAG, "tessdata directory created");
}
return tessdataDirectory.getAbsolutePath();
}
}
ImageProcessingThread Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.util.Log;
import com.googlecode.tesseract.android.TessBaseAPI;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*
* Async Task to process the image and scan the image using tesseract library.
* Equipped with proper callbacks.
*/
public class ImageProcessingThread extends AsyncTask<Void, Void, Void> {
private EasyOcrScannerListener mOcrScannerListener;
private String filePath;
private Bitmap mBitmap;
private String scannedText;
// trained data file used by Tesseract will be copied in directoryPath/tessdata
private String directoryPath;
private String absoluteDirectoryPath;
private Activity mActivity;
String trainedDataCode;
public ImageProcessingThread(EasyOcrScannerListener ocrScannerListener, String filePath,
String directoryPath, Activity activity, String trainedDataCode) {
this.mOcrScannerListener = ocrScannerListener;
this.filePath = filePath;
this.directoryPath = directoryPath;
this.absoluteDirectoryPath = FileUtils.getDirectory(this.directoryPath);
this.mActivity = activity;
this.trainedDataCode = trainedDataCode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mOcrScannerListener.onOcrScanStarted(this.filePath);
}
#Override
protected Void doInBackground(Void... params) {
processImage();
makeTessdataReady();
scannedText = scanImage();
Log.d(Config.TAG, "Scanned test : " + scannedText);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mOcrScannerListener.onOcrScanFinished(mBitmap, scannedText);
}
private void processImage() {
int imageOrientationCode = getImageOrientation();
Bitmap rawBitmap = getBitmapFromPath();
// Getting the bitmap in right orientation.
this.mBitmap = rotateBitmap(rawBitmap, imageOrientationCode);
}
private Bitmap getBitmapFromPath() {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(this.filePath, bmOptions);
return bitmap;
}
private int getImageOrientation() {
ExifInterface exif = null;
try {
exif = new ExifInterface(this.filePath);
} catch (IOException e) {
e.printStackTrace();
}
assert exif != null;
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
return orientation;
}
private Bitmap rotateBitmap(Bitmap bitmap, int orientation){
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
private String scanImage(){
TessBaseAPI baseApi = new TessBaseAPI();
Log.d(Config.TAG, "Data path : " + FileUtils.getDirectory(this.directoryPath));
baseApi.init(FileUtils.getDirectory(this.directoryPath) + "/", this.trainedDataCode);
baseApi.setImage(this.mBitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
return recognizedText;
}
private void makeTessdataReady(){
// created test data directory if necessary under absoluteDirectoryPath and returns its absolute path.
String tessdirectoryPath = FileUtils.getTessdataDirectory(this.absoluteDirectoryPath);
if (!(new File(tessdirectoryPath+ "/" + this.trainedDataCode + ".traineddata")).exists()) {
try {
AssetManager assetManager = mActivity.getAssets();
InputStream in = assetManager.open("tessdata/" + this.trainedDataCode + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
// Output stream with the location where we have to write the eng.traineddata file.
OutputStream out = new FileOutputStream(tessdirectoryPath + "/" + this.trainedDataCode
+ ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(Config.TAG, "Copied " + " traineddata");
} catch (IOException e) {
Log.e(Config.TAG, "Was unable to copy " + " traineddata " + e.toString());
}
}
else{
Log.d(Config.TAG, "tessdata already present");
}
}
}
I hope you guys can help me. It's been days to figure out what's wrong with this code.......
I guess the problem is that the camera activity does not return RESULT_OK, but RESULT_CANCELED - therefore tesseract is never called. You can verify this e. g. by adding in "Tab2.java" at the start of method "onActivityResult":
Log.d("PictureEdit", "onActivityResult w/ resultCode=" + resultCode + " (is ok: " + (resultCode == RESULT_OK) + " is canceled: " + (resultCode == RESULT_CANCELED) + ")" + " requestCode=" + requestCode);
Why is that so? Because starting with Android 6 (Marshmallow) it is not suffice to just declare the necessary permissions in the manifest. Additionally the permissions must got at runtime from the user.
See here: https://developer.android.com/training/permissions/requesting.html
Here is the code I use for getting permissions to camera and r/w to external storage:
private void checkPermissions(){
if (Build.VERSION.SDK_INT >= 23) {
boolean needWriteExtStorage = checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED;
boolean needCamera = checkSelfPermission(android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED;
if (needWriteExtStorage || needCamera){
String[] permissions = new String[((needWriteExtStorage)?(1):(0)) + ((needCamera)?(1):(0))];
int idx = 0;
if (needWriteExtStorage){
permissions[idx] = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
idx++;
}
if (needCamera){
permissions[idx] = android.Manifest.permission.CAMERA;
idx++;
}
ActivityCompat.requestPermissions(
this, permissions, 1);
}
} else {
//permission is automatically granted on sdk<23 upon installation
//Log.e("testing", "Permission is already granted");
}
}
I am currently developing an Android App, which integrates Google Calendar in it. As we know if we wanted to choose an activity to be the starting activity, we just add the "intent-filter" thingy. I added at my Landing Page activity but when I debug on Emulator, it will auto add the "intent-filter" at my Google Calendar activity part and comment out the one I added at my Landing Page.
This is the code at AndroidManifest.xml
<activity
android:name="com.example.dylicious.mydoctors.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="com.example.dylicious.mydoctors.ViewDocActivity"
android:label="#string/title_activity_view_doc" >
</activity>
<activity
android:name="com.example.dylicious.mydoctors.ViewDoctorProf"
android:label="#string/title_activity_view_doctor_prof" >
</activity>
<activity
android:name="com.example.dylicious.mydoctors.StorePatientProfile"
android:label="#string/title_activity_store_patient_profile" >
</activity>
<activity
android:name="com.example.dylicious.mydoctors.ViewPatientProfile"
android:label="#string/title_activity_view_patient_profile" >
</activity>
<activity
android:name="com.example.dylicious.mydoctors.AppointmentActivity"
android:label="#string/title_activity_appointment" >
<!--<intent-filter>-->
<!--<action android:name="android.intent.action.MAIN" />-->
<!--<category android:name="android.intent.category.LAUNCHER" />-->
<!--</intent-filter>-->
</activity>
This is the one I edited, AppointmentActivity is the Google Calendar part. I kept commenting out and delete the part in AppointmentActivity and clean solution and etc. but it doesn't work anything. Just want to check if I had miss out anything as I'm just a newbie in the Android App Development field. Thanks a bunch in advance!
While this is the class for AppointmentActivity.java
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.calendar.CalendarScopes;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
public class AppointmentActivity extends Activity {
com.google.api.services.calendar.Calendar mService;
GoogleAccountCredential credential;
private TextView mStatusText;
private TextView mResultsText;
ProgressDialog mProgress;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
static final int REQUEST_ACCOUNT_PICKER = 1000;
static final int REQUEST_AUTHORIZATION = 1001;
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };
/**
* Create the main activity.
* #param savedInstanceState previously saved instance data.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout activityLayout = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
activityLayout.setLayoutParams(lp);
activityLayout.setOrientation(LinearLayout.VERTICAL);
activityLayout.setPadding(16, 16, 16, 16);
ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mStatusText = new TextView(this);
mStatusText.setLayoutParams(tlp);
mStatusText.setTypeface(null, Typeface.BOLD);
mStatusText.setText("Retrieving data...");
activityLayout.addView(mStatusText);
mResultsText = new TextView(this);
mResultsText.setLayoutParams(tlp);
mResultsText.setPadding(16, 16, 16, 16);
mResultsText.setVerticalScrollBarEnabled(true);
mResultsText.setMovementMethod(new ScrollingMovementMethod());
activityLayout.addView(mResultsText);
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Google Calendar API ...");
setContentView(activityLayout);
// Initialize credentials and service object.
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff())
.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
mService = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential)
.setApplicationName("Google Calendar API Android Quickstart")
.build();
}
/**
* Called whenever this activity is pushed to the foreground, such as after
* a call to onCreate().
*/
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
refreshResults();
} else {
mStatusText.setText("Google Play Services required: " +
"after installing, close and relaunch this app.");
}
}
/**
* Called when an activity launched here (specifically, AccountPicker
* and authorization) exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
* #param requestCode code indicating which activity result is incoming.
* #param resultCode code indicating the result of the incoming
* activity result.
* #param data Intent (containing result data) returned by incoming
* activity result.
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
isGooglePlayServicesAvailable();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
}
} else if (resultCode == RESULT_CANCELED) {
mStatusText.setText("Account unspecified.");
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode != RESULT_OK) {
chooseAccount();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Attempt to get a set of data from the Google Calendar API to display. If the
* email address isn't known yet, then call chooseAccount() method so the
* user can pick an account.
*/
private void refreshResults() {
if (credential.getSelectedAccountName() == null) {
chooseAccount();
} else {
if (isDeviceOnline()) {
mProgress.show();
new ApiAsyncTask(this).execute();
} else {
mStatusText.setText("No network connection available.");
}
}
}
/**
* Clear any existing Google Calendar API data from the TextView and update
* the header message; called from background threads and async tasks
* that need to update the UI (in the UI thread).
*/
public void clearResultsText() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mStatusText.setText("Retrieving data…");
mResultsText.setText("");
}
});
}
/**
* Fill the data TextView with the given List of Strings; called from
* background threads and async tasks that need to update the UI (in the
* UI thread).
* #param dataStrings a List of Strings to populate the main TextView with.
*/
public void updateResultsText(final List<String> dataStrings) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (dataStrings == null) {
mStatusText.setText("Error retrieving data!");
} else if (dataStrings.size() == 0) {
mStatusText.setText("No data found.");
} else {
mStatusText.setText("Data retrieved using" +
" the Google Calendar API:");
mResultsText.setText(TextUtils.join("\n\n", dataStrings));
}
}
});
}
/**
* Show a status message in the list header TextView; called from background
* threads and async tasks that need to update the UI (in the UI thread).
* #param message a String to display in the UI header TextView.
*/
public void updateStatus(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mStatusText.setText(message);
}
});
}
/**
* Starts an activity in Google Play Services so the user can pick an
* account.
*/
private void chooseAccount() {
startActivityForResult(
credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
/**
* Checks whether the device currently has a network connection.
* #return true if the device has a network connection, false otherwise.
*/
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
/**
* Check that Google Play services APK is installed and up to date. Will
* launch an error dialog for the user to update Google Play Services if
* possible.
* #return true if Google Play Services is available and up to
* date on this device; false otherwise.
*/
private boolean isGooglePlayServicesAvailable() {
final int connectionStatusCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
} else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
return false;
}
return true;
}
/**
* Display an error dialog showing that Google Play Services is missing
* or out of date.
* #param connectionStatusCode code describing the presence (or lack of)
* Google Play Services on this device.
*/
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
connectionStatusCode,
AppointmentActivity.this,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
}
Thanks!!
omit the intent-filter in your AppointmentActivity AndroidManifest file declaration. since calling action android:name="android.intent.action.MAIN" which defines the main entry point in your application and android:name="android.intent.category.LAUNCHER" means that the entry point should be listed in the application launcher, so you see there can't be 2 main entry points in the application.
I'm developing a nearby places app.
No error in code in normal way, but when I run the project, logcat shows this error.
I've googled a lot but nothing solved my problem.
logcat :
07-26 11:21:44.056: E/AndroidRuntime(1924): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=market://details?id=com.google.android.gms flg=0x80000 pkg=com.android.vending }
MainActivity.java
package in.wptrafficanalyzer.locationnearby;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener{
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=9C:6F:F6:C2:68:9F:EF:26:42:3F:6E:1F:79:8C:18:B3:0E:16:11:A9");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wptrafficanalyzer.locationnearby"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="in.wptrafficanalyzer.locationnearby.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="in.wptrafficanalyzer.locationnearby.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="in.wptrafficanalyzer.locationnearby.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>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="9C:6F:F6:C2:68:9F:EF:26:42:3F:6E:1F:79:8C:18:B3:0E:16:11:A9"/>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
</application>
</manifest>
Please give me your best help.
Thanks in advance
Your device doesn't have play store to handle the market protocol "market://details?id=com.google.android.gms" you need to install play services on that device or run your code on another device that has play services
Edit
this is how you check for play services
int supported = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(supported == 0) // success! do something
Log.v("play services ", " supported");
else
Log.v("play services ", " not supported");
Have you defined it in your manifest.xml, like so
<activity
android:name=".ActivityName"
android:label="#string/label" >
</activity>
My app crashes at the very begining, in the first line of code of the protected void onCreate(Bundle savedInstanceState) method, the line is super.onCreate(savedInstanceState);, and when I debugged it has pointed me to a file (ActivityThread.java) full of errors. There is a lot of import statement not working and lot of unresolved symbols. I never had problems with this file and I wonder if I have changed something important in manifest or build.graddle, because I'm really stuck in android studio and I'm following google tutorials but I've also heard they are deprecated so I'm also following this code. Besides, I've updated today the android studio software and my project weren't there when I've opened, so I had to import it again and I don't know if it can be the cause of the problem. I haven't posted the logcat because it's allmost infinite, but I'll do an edit if necesary. Any help would be appreciated.
This is a screenshot to (ActivityThread.java)
This is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="22"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.alfredo.webapp.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.alfredo.webapp.permission.C2D_MESSAGE"/>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name">
<!-- Required for applications which use Google Play Services. -->
<!-- <meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" /> -->
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|keyboardHidden|screenSize"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MainActivity$GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<!--android:name=".MainActivity$GcmBroadcastReceiver" -->
<intent-filter>
<!--
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="com.example.alfredo.webapp" />
-->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.google.android.gcm.demo.app" />
</intent-filter>
</receiver>
<!--
<service android:name=".MainActivity$GcmIntentService" />
-->
<service android:name=".MainActivity$GcmIntentService" />
</application>
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.example.alfredo.webapp"
minSdkVersion 10
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
}
And main activity:
package com.example.alfredo.webapp;
import android.app.Activity;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
public class MainActivity extends ActionBarActivity {
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String SENDER_ID = "46075xxxx056";
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
private WebView myWebView = null;
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;
String regid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "hola coño");
setContentView(R.layout.activity_main);
//initialize variables
context = getApplicationContext();
gcm = GoogleCloudMessaging.getInstance(this);
prefs = getPreferences(0);
mDisplay = new TextView(getApplicationContext());
// web view
this.myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://mongini.net/guiasdelsur");
//remove shared prefs
/*
SharedPreferences prefs = getGCMPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
*/
/*
SharedPreferences clear_cache = getSharedPreferences("registration_id", MODE_PRIVATE);
SharedPreferences.Editor edit = clear_cache.edit();
edit.clear();
edit.commit();
*/
// Check device for Play Services APK. If check succeeds, proceed with
// GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
Log.i(TAG,"ok");
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
// You need to do the Play Services APK check here too.
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.d(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing registration ID is not guaranteed to work with
// the new app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* #return Application's {#code SharedPreferences}.
*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the registration ID in your app is up to you.
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences. com.example.alfredo.webapp.MainActivity
*/
private void registerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// Save the regid for future use - no need to register again.
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regid);
editor.commit();
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
// Once registration is done, display the registration status
// string in the Activity's UI.
#Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute();
}
private String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
* or CCS to send messages to your app. Not needed for this demo since the
* device sends upstream messages to a server that echoes back the message
* using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://www.example.com/example.php?host=xxxx&dbname=xxx&user=mongini_webapp&pass=xxx&idPush="+regid);
urlConnection = (HttpURLConnection) url.openConnection();
/** Connecting to url */
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}catch(Exception e){
Log.d("Exception url ", e.toString());
}finally {
urlConnection.disconnect();
}
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
//aqui peta
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
//.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
//back device button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.myWebView.canGoBack()) {
this.myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Edit to add logcat (added a very small portion because it's almost infinite):
05-04 08:01:33.850 23385-23454/? E/dalvikvm﹕ Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.ff.a
05-04 08:01:33.880 23385-23454/? E/dalvikvm﹕ Could not find class 'android.app.Notification$Builder', referenced from method com.google.android.gms.common.ff.b
05-04 08:01:36.010 10233-23463/? E/TalkProvider﹕ replaceContactWithContactId: contactId==0!!! pablogarces123#gmail.com, acct=1
05-04 08:01:36.010 10233-23463/? E/TalkProvider﹕ insert presence failed for account=1 username=pablogarces123#gmail.com client_type=2 status= cap=0 priority=0 mode=3
05-04 08:01:36.090 10233-23463/? E/TalkProvider﹕ replaceContactWithContactId: contactId==0!!! pablogarces123#gmail.com, acct=1
05-04 08:01:36.090 10233-23463/? E/TalkProvider﹕ insert presence failed for account=1 username=pablogarces123#gmail.com client_type=2 status= cap=0 priority=0 mode=3
05-04 08:01:37.469 23385-23466/? E/dalvikvm﹕ Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.util.a.b
05-04 08:01:37.469 23385-23466/? E/dalvikvm﹕ Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.util.a.c
05-04 08:01:37.469 23385-23466/? E/dalvikvm﹕ Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.util.a.e
05-04 08:01:37.499 23223-23241/? E/﹕ statfs /mnt/secure/asec failed, errno: 13
05-04 08:01:40.499 23223-23233/? E/﹕ statfs /mnt/secure/asec failed, errno: 13
05-04 08:01:49.679 10207-10207/? E/Launcher﹕ setWindowOpaque()
05-04 08:01:49.729 10207-10207/? E/Launcher﹕ MTP-LAUNCHER: media scanning not yet finished.
05-04 08:01:57.119 10079-23504/? E/PlayerDriver﹕ Creating Non-Tunnel mode playback - uncompressed MIO
05-04 08:01:57.159 10079-23506/? E/PlayerDriver﹕ Creating Non-Tunnel mode playback - uncompressed MIO
05-04 08:01:57.179 10079-23508/? E/PlayerDriver﹕ Creating Non-Tunnel mode playback - uncompressed MIO
05-04 08:01:57.199 10079-23510/? E/PlayerDriver﹕ Creating Non-Tunnel mode playback - uncompressed MIO
05-04 08:01:57.219 10079-23512/? E/PlayerDriver﹕ Creating Non-Tunnel mode playback - uncompressed MIO
05-04 08:01:57.239 10079-23514/? E/PlayerDriver﹕ Creating Non-Tunnel mode playback - uncompressed MIO
05-04 08:02:04.759 23530-23530/? E/dalvikvm﹕ Could not find class 'android.database.sqlite.SQLiteCantOpenDatabaseException', referenced from method com.google.android.gms.plus.provider.PlusProvider.a
05-04 08:02:15.619 10233-10233/? E/AuthorizationBluetoothService﹕ Proximity feature is not enabled.
05-04 08:02:16.169 23602-23602/? E/dalvikvm﹕ Could not find class 'android.database.sqlite.SQLiteCantOpenDatabaseException', referenced from method com.google.android.gms.plus.provider.PlusProvider.a
05-04 08:02:17.359 10233-10233/? E/AuthorizationBluetoothService﹕ Proximity feature is not enabled.
05-04 08:02:25.849 23551-23551/? E/Finsky﹕ [1] InstallerTask.requireInternalStorageOrCancel: Cancel download of com.google.android.gms because insufficient free space
05-04 08:03:25.599 23641-23641/? E/dalvikvm﹕ Could not find class 'android.database.sqlite.SQLiteCantOpenDatabaseException', referenced from method com.google.android.gms.plus.provider.PlusProvider.a
05-04 08:03:26.139 10233-10233/? E/AuthorizationBluetoothService﹕ Proximity feature is not enabled.
05-04 08:03:26.759 23641-23656/? E/dalvikvm﹕ Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.ff.a
05-04 08:03:26.759 23641-23656/? E/dalvikvm﹕ Could not find class 'android.app.Notification$Builder', referenced from method com.google.android.gms.common.ff.b
05-04 08:03:27.959 23641-23656/? E/dalvikvm﹕ Could not find class 'android.security.KeyPairGeneratorSpec$Builder', referenced from method com.google.android.gms.auth.e.a.a
05-04 08:03:30.809 23641-23664/? E/dalvikvm﹕ Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.util.a.b
I've finally started a new project from scratch, copied the code and figured it was because I were extending actionBarActivity (deprecated) instead of Activity, and it looks like this class need a theme and I weren't using one. Thank you very much to all who has answered or read my question.
I'm trying to make a web app with push notifications. I'm using server key with no ip adress filtering so any ip is allowed (when I was adding my public shared ip from my server I was getting a 404 forbiden error...)
Now it looks like it works, when I send a message I get this :
{"multicast_id":768704xxxxx3856470,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1430054xxxxxx71%60cd63d3f9fd7ecd"}]}{"registration_ids":["APAxxxea-Q0s5pbFZHpSu4BfKdabxxxxxxxxWjPGItVSc54U6_t7WsJme5Z5UjYldhry66rTHk95CUcRR7m2iAtfvPgTklbWlHn4YiDZi1Qxxxxxxxg9iz5jKMPiulvIQTTM5F16THVjw"],"data":{"message":"New content available!"}}
But I never receive a push in my device. I've been following tutorials form google and also form StackOverflow answers, but I'm still very noob in android and I'm sure there is something wrong in my code and I can't figure out what it is, any help would be greatly appreciated.
main activity:
package com.example.alfredo.webapp;
import android.app.Activity;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
public class MainActivity extends ActionBarActivity {
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String SENDER_ID = "xxxxxxxxxxxx";
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
private WebView myWebView = null;
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;
String regid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "hola coño");
setContentView(R.layout.activity_main);
//initialize variables
context = getApplicationContext();
gcm = GoogleCloudMessaging.getInstance(this);
prefs = getPreferences(0);
mDisplay = new TextView(getApplicationContext());
// web view
this.myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://mongini.net/guiasdelsur");
//remove shared prefs
/*
SharedPreferences prefs = getGCMPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
*/
/*
SharedPreferences clear_cache = getSharedPreferences("registration_id", MODE_PRIVATE);
SharedPreferences.Editor edit = clear_cache.edit();
edit.clear();
edit.commit();
*/
// Check device for Play Services APK. If check succeeds, proceed with
// GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
Log.i(TAG,"ok");
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
// You need to do the Play Services APK check here too.
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.d(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing registration ID is not guaranteed to work with
// the new app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* #return Application's {#code SharedPreferences}.
*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the registration ID in your app is up to you.
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences. com.example.alfredo.webapp.MainActivity
*/
private void registerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// Save the regid for future use - no need to register again.
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regid);
editor.commit();
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
// Once registration is done, display the registration status
// string in the Activity's UI.
#Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute();
}
private String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
* or CCS to send messages to your app. Not needed for this demo since the
* device sends upstream messages to a server that echoes back the message
* using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://www.mongini.net/android.php?host=localhost&dbname=bdapp&user=user&pass=pass&idPush="+regid);
urlConnection = (HttpURLConnection) url.openConnection();
/** Connecting to url */
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}catch(Exception e){
Log.d("Exception url ", e.toString());
}finally {
urlConnection.disconnect();
}
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
//aqui peta
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
//.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
//back device button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.myWebView.canGoBack()) {
this.myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alfredo.webapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.alfredo.webapp.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.alfredo.webapp.permission.C2D_MESSAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<receiver
android:name=".MainActivity$GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
</receiver>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="com.example.alfredo.webapp" />
</intent-filter>
</activity>
<service android:name=".MainActivity$GcmIntentService" />
</application>
</manifest>
build gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.example.alfredo.webapp"
minSdkVersion 10
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
}
It will be hard to find the real solution without fixing your BroadcastReceiver implementation first.
It looks like you are following a deprecated sample. In the manifest, you no longer need the com.google.android.c2dm.intent.REGISTRATION action. Also, your receiver tag/entry should be outside the activity tag, and it should have an intent filter (your intent filter is outside the receiver tag).
Hope this leads you to a solution. You might want to follow this sample code instead.