I'm totally new to Android and I decided to create a Siri look-a-like app, which is working fine, I searched before asking but I can't get it to work: Android speech Recognition App Without Pop Up
So I want to hide the pop-up inside my Android app, but I really don't now how to do it properly. I'll be very glad if someone could help me doing this. I have already added the correct permissions in Android Manifest...
Here is my full source:
/**
* Giovanni Terlingen
* PWS Project
* 3 november 2014
* Original file from http://github.com/gi097/PWS
*/
package nl.giovanniterlingen.pws;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnInitListener {
private static final String TAG = "PWS";
private TextView result;
private TextToSpeech tts;
private Button speak;
private int SPEECH_REQUEST_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
speak = (Button) findViewById(R.id.bt_speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRecognizeIntent();
}
});
speak.setEnabled(false);
result = (TextView) findViewById(R.id.tv_result);
tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
speak.setEnabled(true);
} else {
// failed to init
finish();
}
}
private void sendRecognizeIntent() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Aan het luisteren...");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100);
startActivityForResult(intent, SPEECH_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SPEECH_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches.size() == 0) {
tts.speak("Ik heb niks gehoord, probeer het nog eens",
TextToSpeech.QUEUE_FLUSH, null);
} else {
String mostLikelyThingHeard = matches.get(0);
result.setText("Dit heeft u gezegd: "
+ mostLikelyThingHeard + ".");
mostLikelyThingHeard = mostLikelyThingHeard.toLowerCase();
boolean found = false;
String[] groeten = { "hallo", "heey", "hoi", "hey", "he",
"hee", "hay" };
for (String strings : groeten) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Hey leuk dat je er bent!",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] okay = { "oké, oke, ok, okay, okee" };
for (String strings : okay) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Okiedokie!",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] vragen = { "hoe gaat het", "hoe gaat het met je", "hoe gaat het met jou", "hoe gaat het met u", "hoe is het"};
for (String strings : vragen) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Met mij gaat het altijd goed, met jou?",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] wie = { "wie ben", "hoe heet je", "hoe heet jij", "wat is je naam", "wat is uw naam"};
for (String strings : wie) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Ik ben PWS, ik ben gemaakt als profielwerkstuk door Giovanni Terlingen.",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] leeftijd = { "hoe oud ben" };
for (String strings : leeftijd) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Ik ben op 3 november 2014 van start gegaan dus dat mag je zelf uitrekenen",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
String[] lachen = { "haha", "hah", "ha" };
for (String strings : okay) {
if (mostLikelyThingHeard.contains(strings)) {
tts.speak("Haha leuk grapje",
TextToSpeech.QUEUE_FLUSH, null);
found = true;
break;
}
}
if (!found) {
String doei = "doei";
if (mostLikelyThingHeard.equals(doei)) {
tts.speak("Okay tot de volgende keer!",
TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak("Ik begrijp niet wat je bedoeld met "
+ mostLikelyThingHeard
+ " probeer het anders te verwoorden.",
TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
} else {
Log.d(TAG, "result NOT ok");
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
if (tts != null) {
tts.shutdown();
}
super.onDestroy();
}
}
Step 1
In Android Manifest.xml, add the permission.
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Step 2
In the Layout screen, i am using a Toggle Button to start/stop voice listening.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
.......
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="ToggleButton" />
......
</RelativeLayout>
Step 3 - Activity Class
package com.example.voice;
import java.util.ArrayList;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;
public class VoiceRecognitionActivity extends Activity implements
RecognitionListener {
private TextView returnedText;
private ToggleButton toggleButton;
private SpeechRecognizer speech = null;
private Intent recognizerIntent;
private String LOG_TAG = "VoiceRecognitionActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
returnedText = (TextView) findViewById(R.id.textView1);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
speech.startListening(recognizerIntent);
} else {
speech.stopListening();
}
}
});
}
#Override
public void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
if (speech != null) {
speech.destroy();
Log.i(LOG_TAG, "destroy");
}
}
#Override
public void onBeginningOfSpeech() {
Log.i(LOG_TAG, "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.i(LOG_TAG, "onBufferReceived: " + buffer);
}
#Override
public void onEndOfSpeech() {
Log.i(LOG_TAG, "onEndOfSpeech");
toggleButton.setChecked(false);
}
#Override
public void onError(int errorCode) {
String errorMessage = getErrorText(errorCode);
Log.d(LOG_TAG, "FAILED " + errorMessage);
returnedText.setText(errorMessage);
toggleButton.setChecked(false);
}
#Override
public void onEvent(int arg0, Bundle arg1) {
Log.i(LOG_TAG, "onEvent");
}
#Override
public void onPartialResults(Bundle arg0) {
Log.i(LOG_TAG, "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle arg0) {
Log.i(LOG_TAG, "onReadyForSpeech");
}
#Override
public void onResults(Bundle results) {
Log.i(LOG_TAG, "onResults");
ArrayList<String> matches = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String text = "";
for (String result : matches)
text += result + "\n";
returnedText.setText(text);
}
#Override
public void onRmsChanged(float rmsdB) {
Log.i(LOG_TAG, "onRmsChanged: " + rmsdB);
}
public static String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network timeout";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "error from server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No speech input";
break;
default:
message = "Didn't understand, please try again.";
break;
}
return message;
}
}
Related
I'm trying to build a twitter image, video, and gif downloader app on Android Studio.
*I'm able to download video and gif files but I'm unable to download images. It gives me an error when I put Twitter image URL in Edittext:
java.lang.NullPointerException: Attempt to read from field
'java.util.List
com.twitter.sdk.android.core.models.VideoInfo.variants' on a null
object reference
*The error in code : url = result.data.extendedEntities.media.get(0).videoInfo.variants.get(i).url; How can I achieve to download images from Twitter URL?
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.esafirm.rxdownloader.RxDownloader;
import com.shid.twittervideo.R;
import com.shid.twittervideo.util.Constant;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.DefaultLogger;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterConfig;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.core.services.StatusesService;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;
public class MainActivity extends AppCompatActivity {
private Button btn_download, btn_paste;
private ProgressDialog progressDialog;
private TextView txt_url;
private ClipboardManager clipboardManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUI();
btnClick();
checkPermission();
setTwitterConfig();
}
public void setTwitterConfig() {
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(Constant.TWITTER_KEY, Constant.TWITTER_SECRET))
.debug(true)
.build();
Twitter.initialize(config);
}
#SuppressLint("ClickableViewAccessibility")
public void setUI() {
btn_download = findViewById(R.id.btn_download);
txt_url = findViewById(R.id.txt_tweet_url);
btn_paste = findViewById(R.id.btn_paste);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Fetching video....");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
txt_url.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (txt_url.getRight() - txt_url.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
txt_url.setText("");
return true;
}
}
return false;
}
});
}
public void btnClick() {
btn_paste.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
CharSequence textToPaste = clipboardManager.getPrimaryClip().getItemAt(0).getText();
txt_url.setText(textToPaste);
} catch (Exception e) {
return;
}
}
});
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname;
//Check if the tweet url field has text containing twitter.com/...
if (txt_url.getText().length() > 0 && txt_url.getText().toString().contains("twitter.com/")) {
Long id = getTweetId(txt_url.getText().toString());
fname = String.valueOf(id);
//Call method to get tweet
if (id != null) {
getTweet(id, fname);
} else {
alertNoUrl();
}
} else{
alertNoUrl();
}
}
});
}
public void checkPermission() {
//If we don't have permission we prompt the user
if (!storageAllowed()) {
ActivityCompat.requestPermissions(this, Constant.PERMISSION_STRORAGE, Constant.REQUEST_EXTERNAL_STORAGE);
}
}
private void getTweet(Long id, String fname) {
progressDialog.show();
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
StatusesService statusesService = twitterApiClient.getStatusesService();
Call<Tweet> tweetCall = statusesService.show(id, null, null, null);
tweetCall.enqueue(new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
Log.d("MartianDeveloper", ""+result.data.extendedEntities.media.get(0).type);
//Check if media is present
if (result.data.extendedEntities == null && result.data.entities.media == null) {
alertNoMedia();
} else if (result.data.extendedEntities != null) {
if (!(result.data.extendedEntities.media.get(0).type).equals("video") &&
!(result.data.extendedEntities.media.get(0).type).equals("animated_gif") && !(result.data.extendedEntities.media.get(0).type).equals("photo")) {
alertNoVideo();
} else {
String filename = fname;
String url;
//Set filename to gif or mp4
if ((result.data.extendedEntities.media.get(0).type).equals("video") ||
(result.data.extendedEntities.media.get(0).type).equals("animated_gif")) {
filename = filename + ".mp4";
Log.d("TAG", "filenme for video is " + filename);
}else if ((result.data.extendedEntities.media.get(0).type).equals("photo")){
filename = filename + ".jpg";
}
int i = 0;
url = result.data.extendedEntities.media.get(0).videoInfo.variants.get(i).url;
Log.d("TAG", "url is " + url);
while (!url.contains(".mp4")) {
try {
if (result.data.extendedEntities.media.get(0).videoInfo.variants.get(i) != null) {
url = result.data.extendedEntities.media.get(0).videoInfo.variants.get(i).url;
Log.d("TAG", "url2 is " + url);
i += 1;
}
} catch (IndexOutOfBoundsException e) {
downloadVideo(url, filename);
}
}
downloadVideo(url, filename);
}
}
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(MainActivity.this, "Request failed, check your Internet connection", Toast.LENGTH_SHORT).show();
}
});
}
private void downloadVideo(String url, String filename) {
//Check if External Storage permission js allowed
if (!storageAllowed()) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(this, Constant.PERMISSION_STRORAGE, Constant.REQUEST_EXTERNAL_STORAGE);
progressDialog.hide();
Toast.makeText(this, "Kindly grant the request and try again", Toast.LENGTH_SHORT).show();
} else {
RxDownloader rxDownloader = new RxDownloader(MainActivity.this);
rxDownloader.download(url, filename, "video/*", true)
.subscribe(new Observer<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(String s) {
}
#Override
public void onError(Throwable e) {
Toast.makeText(MainActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete() {
Toast.makeText(MainActivity.this, "Download Complete", Toast.LENGTH_SHORT).show();
}
});
progressDialog.hide();
Toast.makeText(this, "Download Started: Check Notification", Toast.LENGTH_LONG).show();
}
}
private void alertNoVideo() {
progressDialog.hide();
Toast.makeText(this, "URL entered do not contain any video or gif", Toast.LENGTH_SHORT).show();
}
private void alertNoMedia() {
progressDialog.hide();
Toast.makeText(this, "The link entered do not contain any media", Toast.LENGTH_SHORT).show();
}
private Long getTweetId(String s) {
Log.d("TAG", "link is :" + s);
try {
String[] split = s.split("\\/");
String id = split[5].split("\\?")[0];
return Long.parseLong(id);
} catch (Exception e) {
Log.d("TAG", "getTweetId: " + e.getLocalizedMessage());
alertNoUrl();
return null;
}
}
private void alertNoUrl() {
Toast.makeText(this,getResources().getString(R.string.toast_url) , Toast.LENGTH_LONG).show();
}
//Method that checks the permission depending on the version of the phone
private boolean storageAllowed() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permission = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
return permission == PackageManager.PERMISSION_GRANTED;
}
return true;
}
}
I just put this code to retrieve the image result.data.extendedEntities.media.get(0).mediaUrl
Please help!!!
I am creating a screen capture application and the problem is that after clicking the PRO button and after the purchase, the ads and the button do not hide.
I am trying to remove a button and ads using layout changes:
setContentView (R.layout.main_pro)
the code:
IabHelper.OnIabPurchaseFinishedListener () {
#Override
public void onIabPurchaseFinished (IabResult result, purchase purchase) {
if (result.isFailure ()) {
Log.d (TAG, "Purchase Error:" result);
return;
}
even if (purchase.getSku (). equals (SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView (R.layout.main_pro);
remove ads ();
Toast.makeText (MainActivity.this, “The purchase was successful,” Toast.LENGTH_LONG) .show ();
}
}
};
}
Full code:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.icu.text.SimpleDateFormat;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.ViewFlipper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.davidgrigoryan.screenrecorder.util.Constants;
import com.davidgrigoryan.screenrecorder.util.IabHelper;
import com.davidgrigoryan.screenrecorder.util.IabResult;
import com.davidgrigoryan.screenrecorder.util.Inventory;
import com.davidgrigoryan.screenrecorder.util.Purchase;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE = 1000;
private int mScreenDensity;
File file;
private Context context;
private ShareActionProvider mShareActionProvider;
private MediaProjectionManager mProjectionManager;
private static final int DISPLAY_WIDTH = 720;
private static final int DISPLAY_HEIGHT = 1280;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
static final String SKU_REMOVE_ADS = "android.test.purchased";
static final int RC_REQUEST = 10111;
private MediaProjectionCallback mMediaProjectionCallback;
private MediaRecorder mMediaRecorder;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private static final int REQUEST_PERMISSION_KEY = 1;
boolean isRecording = false;
private FloatingActionButton rec;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private Intent intent;
private Activity activity;
private boolean URL_TO_SHARE;
private ImageView wm;
private NotificationManagerCompat notificationManager;
private String title;
private String message;
private InterstitialAd mInterstitialAd;
private String testDeviceId;
AdRequest adRequest;
private AdView adView;
IabHelper mHelper;
String base64EncodedPublicKey = "PublicKey";
Boolean isAdsDisabled = false;
String payload = "Upgrade PRO";
private Inventory i;
private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
private static boolean isWidget = false;
private static Context appContext;
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView pro = (ImageView) findViewById(R.id.buy);
final SharedPreferences prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
pro.setVisibility(prefs.getBoolean("isPurchase", true) ? View.VISIBLE : View.INVISIBLE);
pro.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
purchaseRemoveAds();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Handler handler = new Handler();
final Timer timer = new Timer();
final TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 120000);
adView = (AdView) findViewById(R.id.adView);
adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-9842509861911521/3646081879");
AdRequest adRequestInterstitial = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest adRequestBanner = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(testDeviceId)
.build();
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
AdSize adSize = new AdSize(320, 50);
MobileAds.initialize(getApplicationContext(), "ca-app-pub-9842509861911521/3646081879");
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-9842509861911521/1961271598");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
};
if (!Service.hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_KEY);
}
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mMediaRecorder = new MediaRecorder();
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
rec = (FloatingActionButton) findViewById(R.id.rec);
rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onToggleScreenShare();
}
});
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(false);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#Override
public void onIabSetupFinished(IabResult result, IabHelper.QueryInventoryFinishedListener mGotInventoryListener) throws IabHelper.IabAsyncInProgressException {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
return;
}
if (mHelper == null)
return;
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
queryPurchased();
IabHelper.OnIabPurchaseFinishedListener mPurchasedFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView(R.layout.main_pro);
removeAds();
Toast.makeText(MainActivity.this,"Purchase successful",Toast.LENGTH_LONG).show();
}
}
};
}
private void queryPurchased() {
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else{
// does the user have the premium upgrade?
isAdsDisabled = inventory.hasPurchase(SKU_REMOVE_ADS);
// update UI accordingly
}
}
};
}
public void purchaseRemoveAds() {
try {
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, SKU_REMOVE_ADS, 9, mPurchaseFinishedListener, "SECURITYSTRING");
} catch (Exception e) {
e.printStackTrace();
mHelper.flagEndAsync();
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.error)
.setMessage(R.string.error_play_store)
.setPositiveButton("OK", null)
.show();
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG, "Purchase finished: " + result + ", purchase: "
+ purchase);
if (mHelper == null)
return;
if (result.isFailure()) {
return;
}
if (!verifyDeveloperPayload(purchase)) {
return;
}
if (isAdsDisabled == true){
setContentView(R.layout.main_pro);
}
Log.d(TAG, "Purchase successful.");
if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
removeAds();
}
}
};
}
private void removeAds() {
adView.setEnabled(false);
adView.setVisibility(View.INVISIBLE);
}
public void onToggleScreenShare() {
if (!isRecording) {
Toast.makeText(getApplicationContext(), R.string.start_rec, Toast.LENGTH_LONG).show();
startService();
initRecorder();
shareScreen();
} else {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ads not loaded!");
}
Toast.makeText(getApplicationContext(), R.string.stop_rec, Toast.LENGTH_LONG).show();
stopService();
mMediaRecorder.stop();
mMediaRecorder.reset();
stopScreenSharing();
}
}
private void shareScreen() {
if (mMediaProjection == null) {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
return;
}
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
private VirtualDisplay createVirtualDisplay() {
return mMediaProjection.createVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
}
private void initRecorder() {
try {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //THREE_GPP
mMediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(16); // 30
mMediaRecorder.setVideoEncodingBitRate(3000000);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mMediaRecorder.setOrientationHint(orientation);
mMediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
private File initFile() {
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator + "ScreenRecorder");
if (!dir.exists() && !dir.mkdirs()) {
Log.wtf(TAG,
R.string.error_folder
+ dir.getAbsolutePath());
file = null;
} else {
file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
"'VIDEO-'yyyyMMddHHmmss'.mp4'").format(new Date()));
}
return file;
}
private void stopScreenSharing() {
if (mVirtualDisplay == null) {
return;
}
mVirtualDisplay.release();
destroyMediaProjection();
isRecording = false;
}
private void destroyMediaProjection() {
if (mMediaProjection != null) {
mMediaProjection.unregisterCallback(mMediaProjectionCallback);
mMediaProjection.stop();
mMediaProjection = null;
}
Log.i(TAG, "MediaProjection Stopped");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != REQUEST_CODE) {
Log.e(TAG, "Unknown request code: " + requestCode);
return;
}
if (resultCode != RESULT_OK) {
Toast.makeText(this, R.string.denied, Toast.LENGTH_SHORT).show();
isRecording = false;
return;
}
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
} else
Log.d(TAG, "onActivityResult handled by IABUtil.");
mMediaProjectionCallback = new MediaProjectionCallback();
mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
mMediaProjection.registerCallback(mMediaProjectionCallback, null);
mVirtualDisplay = createVirtualDisplay();
mMediaRecorder.start();
isRecording = true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_KEY: {
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
onToggleScreenShare();
} else {
isRecording = false;
Snackbar.make(findViewById(android.R.id.content), R.string.message,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.enable,
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}).show();
}
return;
}
}
}
private class MediaProjectionCallback extends MediaProjection.Callback {
#Override
public void onStop() {
if (isRecording) {
isRecording = false;
mMediaRecorder.stop();
mMediaRecorder.reset();
}
mMediaProjection = null;
stopScreenSharing();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onDestroy() {
if (mHelper != null)
try {
mHelper.dispose();
mHelper = null;
} catch (IabHelper.IabAsyncInProgressException e) {
e.printStackTrace();
}
if (adView != null) {
adView.destroy();
}
super.onDestroy();
destroyMediaProjection();
}
private void about() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle(R.string.about);
builder1.setMessage(R.string.description);
builder1.setCancelable(true);
builder1.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#SuppressLint("ResourceType")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
about();
return true;
case R.id.share:
shareApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void shareApp() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
#SuppressLint({"StringFormatInvalid", "LocalSuppress"})
String extraText = getString(R.string.share_desc, getString(R.string.link));
intent.putExtra(Intent.EXTRA_TEXT, extraText);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
public void startService() {
Intent serviceIntent = new Intent(this, Background.class);
serviceIntent.putExtra("inputExtra", "Notification");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, Background.class);
stopService(serviceIntent);
}
boolean verifyDeveloperPayload(Purchase p) {
String payload = p.getDeveloperPayload();
return true;
}
}
And it looks like this:
What am I doing wrong? How can I fix this?
Thanks for any help!
I want to make an application which can speak a different language, the text of which which will be written in a text field, which may be English, Bengali or any other language. I use this code but can not speak in different language. It is always speaking in English or which language I set in Google-Text-speech from phone setting.
Here is my java code
package com.example.texttospeech;
import android.util.Log;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
TextToSpeech tts;
EditText input;
TextView TextCount;
Button b1, b2;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.editText);
TextCount = (TextView) findViewById(R.id.TextCount);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
tts = new TextToSpeech(this, this);
TextCountNow();
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String text = input.getText().toString();
if (text.isEmpty()) {
String EmptyText = "Nothing found in text fild. please Write something to read.";
tts.speak(EmptyText, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(MainActivity.this, "Text is empty", Toast.LENGTH_LONG).show();
} else if (text.length() > 5000) {
String FaildText = "Text Ought of length. Maximum length is 5000. Please remove some text and try again";
tts.speak(FaildText, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(), "Ought of length. Maximum length is 5000.", Toast.LENGTH_LONG).show();
} else {
String ReadingText = text + ". Text reading completed";
tts.speak(ReadingText, TextToSpeech.QUEUE_FLUSH, null);
}
break;
case R.id.button1:
input.setText("");
break;
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
#SuppressWarnings("deprecation")
Locale bahasa = tts.getLanguage();
int result = tts.setLanguage(bahasa);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "This Language is not supported", Toast.LENGTH_SHORT).show();
Log.e("TTS", "This Language is not supported");
} else {
//do nathing
}
} else {
Log.e("TTS", "initialization faild");
}
}
public void TextCountNow(){
final Handler h = new Handler();
Runnable r = new Runnable() {
public void run() {
int textLanth = input.getText().length();
TextCount.setText("" + textLanth);
h.postDelayed(this, 500);
}
};
h.postDelayed(r, 500);
}
}
For Bengali Language :
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
int result = textToSpeechService.setLanguage(new Locale("bn"));
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED
) {
Toast.makeText(mContext, "Speech Service Not Ready", Toast.LENGTH_SHORT).show();
} else {
textToSpeechService.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
stopBanglaReading();
}
#Override
public void onError(String utteranceId) {
}
});
int voicePitch = settings.getInt("ExplVoicePitch", 10);
int voiceSpeed = settings.getInt("ExplVoiceSpeed", 8);
textToSpeechService.setSpeechRate((float) voiceSpeed / 10);
textToSpeechService.setPitch((float) voicePitch / 10);
startSpeaking(onubad);
}
} else {
Toast.makeText(mContext, "Speech Service Not Ready, Please Try Again....", Toast.LENGTH_LONG).show();
}
}
});
I am using a Bluetooth printer and zxing barcode scanner for this project. My problem is that after I have the Bluetooth printer connected and I try to scan a barcode, using zxing, it disconnects the Bluetooth printer. Here is my code.
package com.zj.printdemo;
import com.zj.printdemo.R;
import android.app.Fragment;
import android.content.Intent;
import com.zj.btsdk.BluetoothService;
import com.zj.btsdk.PrintPic;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.view.View.OnClickListener;
import android.util.Log;
import android.view.ViewGroup;
public class PrintDemo extends Activity {
Button btnSearch;
Button btnSendDraw;
Button btnSend;
//Button btnClose;
Button clearBtn;
Button btnBarcode;
EditText edtContext;
EditText edtContextQTY;
EditText edtPrint;
private static final int REQUEST_ENABLE_BT = 2;
BluetoothService mService = null;
BluetoothDevice con_dev = null;
private static final int REQUEST_CONNECT_DEVICE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
//Button clearBtn = (Button)findViewById(R.id.btnClear);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//edtContext = (EditText) findViewById(R.id.txt_content);
mService = new BluetoothService(this, mHandler);
if( mService.isAvailable() == false ){
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
clearBtn = (Button)findViewById(R.id.btnClear);
OnClickListener ClearOnClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
edtContext.setText("");
edtContextQTY.setText("");
}
};
clearBtn.setOnClickListener(ClearOnClickListener);
btnBarcode = (Button) findViewById(R.id.btnBarcode);
OnClickListener BarcodeOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnBarcode) {
IntentIntegrator integrator = new IntentIntegrator(PrintDemo.this);
integrator.initiateScan();
}
}
};
btnBarcode.setOnClickListener(BarcodeOnClickListener);
}
public void onStart() {
super.onStart();
if( mService.isBTopen() == false)
{
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_test);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new ClickEvent());
//btnClose = (Button) this.findViewById(R.id.btnClose);
//btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
edtContextQTY = (EditText) findViewById(R.id.txt_contentQTY);
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("������Ϣ",ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this,DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
String msg = edtContext.getText().toString();
String msgQTY = edtContextQTY.getText().toString();
if( msg.length() > 0 ){
mService.sendMessage("ItemID:"+msg+"\n","ItemQTY:"+msgQTY+"\n");
}
} //else if (v == btnClose) {
//mService.stop();}
else if (v == btnSendDraw) {
String msg = "";
String lang = getString(R.string.strLang);
//printImage();
byte[] cmd = new byte[3];
cmd[0] = 0x1b;
cmd[1] = 0x21;
if((lang.compareTo("en")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("Congratulations!\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " You have sucessfully created communications between your device and our bluetooth printer.\n\n"
+" the company is a high-tech enterprise which specializes" +
" in R&D,manufacturing,marketing of thermal printers and barcode scanners.\n\n";
mService.sendMessage(msg,"GBK");
}else if((lang.compareTo("ch")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("��ϲ����\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " ���Ѿ��ɹ��������������ǵ�������ӡ����\n\n"
+ " ����˾��һ��רҵ�����з�����������������Ʊ�ݴ�ӡ��������ɨ���豸��һ��ĸ߿Ƽ���ҵ.\n\n";
mService.sendMessage(msg,"GBK");
}
}
}
}
/**
* Handler BluetoothService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("��������","��������.....");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("StateNone","�ȴ�����.....");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
case IntentIntegrator.REQUEST_CODE:
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
//formatTxt.setText("FORMAT: " + scanFormat);
edtContext.setText(scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData = null;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, "/mnt/sdcard/icon.jpg");
sendData = pg.printDraw();
mService.write(sendData);
}
}
My goal is to connect the printer, scan a barcode, and print a tag with the ID and quantity. Manual entry works, the printer works, and the barcode scanning works. Its only when you use the barcode scanner after you connect the printer that it will disconnect the printer.
Getting an error while runtime how to resolve this plz help me out with as i am stucked in it i am a beginner
getting log cat error
Binary XML file line #41: Error inflating class com.facebook.login.widget.LoginButton
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_below="#id/signInText"
android:background="#drawable/facebook_connect"
/>
Home Activity
package com.styllonz.activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.google.gson.Gson;
import com.styllonz.R;
import com.styllonz.fragments.ForgotPasswordFragment;
import com.styllonz.fragments.LandingFragment;
import com.styllonz.fragments.LoginFragment;
import com.styllonz.fragments.SignUpFragment;
import com.styllonz.models.Response;
import com.styllonz.network.BusNetworkCallback;
import com.styllonz.network.WebserviceApi;
import com.styllonz.utils.Constants;
import com.styllonz.utils.Utilities;
import retrofit.RetrofitError;
public class HomeActivity extends FragmentActivity implements LandingFragment.OnFragmentInteractionListener,SignUpFragment.OnFragmentInteractionListener,
LoginFragment.OnFragmentInteractionListener, ForgotPasswordFragment.OnFragmentInteractionListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress, mSignInClicked;
ConnectionResult mConnectionResult;
ProgressDialog progress;
Context mContext;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_home);
if (savedInstanceState == null)
replaceFragment(LandingFragment.newInstance(), LandingFragment.TAG, false);
mSharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
mEditor=mSharedPreferences.edit();
mContext=this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
public void replaceFragment(Fragment fragment, String fragmentTag, boolean addToBackstack) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (addToBackstack)
fragmentManager.beginTransaction()
.replace(R.id.flFragmentHolder, fragment, fragmentTag).addToBackStack("")
.commit();
else
fragmentManager.beginTransaction()
.replace(R.id.flFragmentHolder, fragment, fragmentTag)
.commit();
}
#Override
public void onHomeFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cfbSignUp:
replaceFragment(SignUpFragment.newInstance(), SignUpFragment.TAG, true);
break;
case R.id.cfbLogin:
replaceFragment(LoginFragment.newInstance(), LoginFragment.TAG, true);
break;
}
}
#Override
public void onSignUpFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cftvSignUpTitle:
getSupportFragmentManager().popBackStackImmediate();
}
}
#Override
public void onLoginFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cftvForgotPassword:
replaceFragment(ForgotPasswordFragment.newInstance(), ForgotPasswordFragment.TAG, true);
break;
case R.id.cfbLogin:
Intent mainActivityIntent = new Intent(this, MainActivity.class);
startActivity(mainActivityIntent);
finish();
break;
case R.id.cftvLoginTitle:
getSupportFragmentManager().popBackStackImmediate();
}
}
#Override
public void onBackPressed() {
if (!getSupportFragmentManager().popBackStackImmediate())
super.onBackPressed();
}
#Override
public void onForgotPasswordFragmentInteraction(View view) {
int viewId = view.getId();
switch (viewId) {
case R.id.cftvForgotPasswordTitle:
getSupportFragmentManager().popBackStackImmediate();
}
}
#Override
protected void onStart() {
super.onStart();
//
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
// Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
getProfileInformation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
if(progress!=null&&progress.isShowing())
progress.dismiss();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
resolveSignInError();
}
}
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode,responseCode,intent);
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
/**
* Sign-in into google
*/
public void signInWithGplus() {
if(Utilities.isOnline(this)) {
progress = ProgressDialog.show(this, "",
"Loading...", true);
if (!mSharedPreferences.contains(Constants.SHARED_PREFS_B_GMAIL_SOURCE)||!mGoogleApiClient.isConnected()) {
mSignInClicked = true;
if(mConnectionResult!=null)
resolveSignInError();
else
mGoogleApiClient.connect();
} else if(mGoogleApiClient.isConnected()){
getProfileInformation();
}
else if (mSharedPreferences.getBoolean(Constants.SHARED_PREFS_B_GMAIL_SOURCE, false)) {
login();
}
else {
if(progress!=null)
{
progress.dismiss();
}
}
}
else
{
Toast.makeText(this,"Please connect to internet",Toast.LENGTH_SHORT).show();
}
}
/**
* Method to resolve any signin errors
*/
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
/**
* Fetching user's information name, email, profile pic
*/
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
final Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(getClass().getSimpleName(), "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
final WebserviceApi webserviceApi=Utilities.getWebservice(mContext);
if(webserviceApi!=null)
{
webserviceApi.signupFromSource(email, personName, 'c', "google", "gmail", new BusNetworkCallback<Response>() {
#Override
public void onSuccess(Response obj) {
if (progress != null & progress.isShowing())
progress.dismiss();
Log.d(getClass().getSimpleName(), " success");
if (obj.getResult() != null && obj.getResult().equals("success")) {// Utilities.showAlertDialog(mContext,"Alert","User registered successfully.");
mEditor.putBoolean(Constants.SHARED_PREFS_B_GMAIL_SOURCE, true);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, email);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, currentPerson.getId());
mEditor.commit();
login();
} else if (obj.getError() != null && obj.getError().length() > 0) {
if (obj.getError().contains("Email")) {
mEditor.putBoolean(Constants.SHARED_PREFS_B_GMAIL_SOURCE, true);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, email);
mEditor.putString(Constants.SHARED_PREFS_S_GMAIL_EMAIL, currentPerson.getId());
mEditor.commit();
login();
} else {
Utilities.showAlertDialog(mContext, "Error", obj.getError());
{
if (progress != null & progress.isShowing())
progress.dismiss();
}
}
} else {
Utilities.showAlertDialog(mContext, "Error", "Some error occured please try later");
{
if (progress != null & progress.isShowing())
progress.dismiss();
}
}
}
#Override
public void onFailure(RetrofitError error) {
if (progress != null & progress.isShowing())
progress.dismiss();
super.onFailure(error);
}
});
}
else
{
if(progress!=null)
{
progress.dismiss();
}
}
} else {
Toast.makeText(getApplicationContext(),
"No information found from google", Toast.LENGTH_LONG).show();
if(progress!=null&progress.isShowing())
progress.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"No information found from google", Toast.LENGTH_LONG).show();
if(progress!=null&progress.isShowing())
progress.dismiss();
}
}
private void login() {
WebserviceApi webserviceApi=Utilities.getWebservice(this);
if(webserviceApi!=null) {
if (mSharedPreferences.contains(Constants.SHARED_PREFS_S_GMAIL_EMAIL))
webserviceApi.loginFromSource(Constants.SHARED_PREFS_S_GMAIL_EMAIL , Constants.SHARED_PREFS_S_GMAIL_ID,
new BusNetworkCallback<Response>() {
#Override
public void onSuccess(Response obj) {
progress.dismiss();
Log.d(getClass().getSimpleName(), " success");
if (obj.getResult() != null && obj.getResult().equals("success")) {
Constants.userDetails = obj.getData();
Gson gson = new Gson();
mEditor.putString(Constants.SHARED_PREFS_S_USER_DETAILS, gson.toJson(Constants.userDetails));
mEditor.commit();
Intent mainActivityIntent = new Intent(mContext, MainActivity.class);
startActivity(mainActivityIntent);
finish();
} else if (obj.getError() != null && obj.getError().length() > 0)
Utilities.showAlertDialog(mContext, "Error", obj.getError());
else
Utilities.showAlertDialog(mContext, "Error", "Some error occurred. Please try again later.");
}
#Override
public void onFailure(RetrofitError error) {
if(progress!=null&progress.isShowing())
progress.dismiss();
super.onFailure(error);
Utilities.showAlertDialog(mContext, "Error", "Some error occurred. Please try again later.");
}
}
);
}
else
{
if(progress!=null&progress.isShowing())
progress.dismiss();
}
}
}