I want my application to auto launch an activity when beacon comes within a certain distance (in my case it is 1 meter)
My activity gets launched when i plug in or plug off the charger and when i boot the device but it didn't get auto launch when i closed the application and beacon is in 1 meter.
what i want is if beacon is in 1 meter then activity should launch by itself.
I am using android beacon library and following the same steps mentioned on
https://altbeacon.github.io/android-beacon-library/samples.html
My manifest file code is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.altbeacon.beaconreference"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="org.altbeacon.beaconreference.MyApplicationName">
<activity
android:launchMode="singleInstance"
android:name="org.altbeacon.beaconreference.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>
</manifest>
My application class code is :
import java.util.Collection;
import android.app.Application;
import android.content.Intent;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.BootstrapNotifier;
import org.altbeacon.beacon.startup.RegionBootstrap;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
public class MyApplicationName extends Application implements BootstrapNotifier, RangeNotifier {
private static final String TAG = ".MyApplicationName";
private RegionBootstrap regionBootstrap;
private BeaconManager mBeaconManager;
private Region region;
private Region mAllBeaconsRegion;
private BackgroundPowerSaver mBackgroundPowerSaver;
private RegionBootstrap mRegionBootstrap;
#Override
public void onCreate() {
mAllBeaconsRegion = new Region("all beacons", null, null, null);
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBackgroundPowerSaver = new BackgroundPowerSaver(this);
mRegionBootstrap = new RegionBootstrap(this, mAllBeaconsRegion);
// By default the AndroidBeaconLibrary will only find AltBeacons. If you wish to make it
// find a different type of beacon, you must specify the byte layout for that beacon's
// advertisement with a line like below. The example shows how to find a beacon with the
// same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb
//
Log.d(TAG, " region. starting ranging");
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
mBeaconManager.setBackgroundScanPeriod(11000l);
}
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// Don't care
}
#Override
public void didEnterRegion(Region arg0) {
mRegionBootstrap.disable();
// This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
// if you want the Activity to launch every single time beacons come into view, remove this call.
try {
mBeaconManager.startRangingBeaconsInRegion(new Region("all beacons", null, null, null));
mBeaconManager.setRangeNotifier(this);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "Got a didEnterRegion call");
}
#Override
public void didExitRegion(Region arg0) {
// Don't care
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
// TODO Auto-generated method stub
if (beacons.size() > 0) {
for (Beacon beacon: beacons) {
if(beacon.getDistance()<1)
{
Log.d(TAG, "within 1 minute call");
Intent intent = new Intent(this, MainActivity.class);
// IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
// created when a user launches the activity manually and it gets launched from here.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
}
}
}
}
My Main activity class is:
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The behavior of the Android Beacon Library after an app is closed is different depending on how it was closed. Beacon scanning keep going at background rates (once every 5 minutes on Android 4.x) if you use the back button. If you kill it with the task switcher, it will resume scanning as soon vas possible (on power connected/disconnected or reboot).
Full details here: http://altbeacon.github.io/android-beacon-library/resume-after-terminate.html
Your code looks OK to do what you want within the parameters of what is described above. It is possible that you are simply seeing a five minute delay on detections when the app is in the background. Scanning once every five minutes in the background is done to save battery, but is configurable. On Android 5.x this delay is not present if you go from no beacons being visible to beacons being visible.
See here for details: http://altbeacon.github.io/android-beacon-library/battery_manager.html
Related
I am trying to build an app which can turn on and off Camera Flash of my device . In Code its not showing any error but while launching the app on my device it's start to Crash .
Report bug is showing some Unable to start activity and something like Fail to connect Camera Services .
Since I am new in android Development and don't have enough knowledge.
I had already seen few questions regarding this but not able to find some useful information. All answers were approximately suggesting adding using permission in manifest file which I already did.
content of manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.joshiyogesh.flashlight">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
content of Main-activity Java:
package com.example.joshiyogesh.flashlight;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btn;
android.hardware.Camera camera;
Camera.Parameters parameters;
boolean isFlash = false;
boolean isOn = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button2);
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
camera = Camera.open();
parameters = camera.getParameters();
isFlash = true;
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFlash){
if(!isOn){
btn.setText("Off");
btn.setBackgroundColor(Color.GREEN);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isOn = true;
}
else{
btn.setText("ON");
btn.setBackgroundColor(Color.RED);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isOn = false;
}
}
else{
Toast.makeText(MainActivity.this,"Camera Not detecting",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStop() {
super.onStop();
if(camera!=null){
camera.release();
camera = null;
}
}
}
I have uploaded image of report bug of my mobile device
I'm posting the code to open the camera,please make changes as per your need.
try this:
static Camera camera = null;
and declare the following:
try{
if(clickOn == true) {
clickOn = false;
camera = Camera.open();
Parameters parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
remoteViews.setViewVisibility(R.id.button1, View.GONE);
remoteViews.setViewVisibility(R.id.button2, View.VISIBLE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
} else {
clickOn = true;
camera.stopPreview();
camera.release();
camera = null;
remoteViews.setViewVisibility(R.id.button1, View.VISIBLE);
remoteViews.setViewVisibility(R.id.button2, View.GONE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
}
} catch(Exception e) {
Log.e("Error", ""+e);
}
After using camera, Don't forget to release it by following statement:
camera.release();
Also it may be the case that your app is not given permission to open camera at run time. Because from android 6.0 it is necessary to to have runtime permission to do specific tasks.
So if you are using Android 6.0(Marshmallow) or above, please check that the permission is enabled or not by following this:
The permission for camera could be disabled and should be enabled from the app settings. Settings -> Apps -> [Your App] -> Permissions.
That is what worked for me. Hope this help you too :)
EDIT
And please use e.printstacktrace() in your catch block to get error logcat.
i think there is problem while releasing the camera . Since you have written release method in onStop ,your camera will get release only when app is closed. try to release the camera when you are turning off the flash in button click method.
I got where i was wrong . Codes written above are Right . The only problem , i was using marshmallow in which we have to give permission to obtain camera permission through device .
I am a newbie in both in this forum and in Android world. I just developed a singleplayer trivia game, named "Reklamsız Bilgi Yarışması", only supports my local language but accessable in all over the world.
I just followed the guides and integrated AdColony to my AdMob account and get the perfect results, with test video ads.
However, after going live, nothing happened. Many of my customers wrote me that they can not get Ad Videos. Also, in admob, I saw 650 requests happened and only 4 of them get the video!
In AdColony statistics, I saw only 5 lucky guy requested the video and got watched full video, then took their rewards.
So, how could it be? Hundreds of request but only %0.25 of them were answered by AdMob (Or AdColony), I could not understand.
Lastly, %98 percent of my customers are from Turkey, %1 from Azerbaijan and %1 from Germany.
Is there any possible mistake in coding? Because I saw the test ads, on my physical device, not on the emulator also.
Thank You !
<<<<<<<<<<<< In Manıfest >>>>>>>>>>>>>>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
<activity android:name="com.jirbo.adcolony.AdColonyOverlay"
android:configChanges="keyboardHidden|screenSize"
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
<activity android:name="com.jirbo.adcolony.AdColonyFullscreen"
android:configChanges="keyboardHidden|screenSize"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" />
<activity android:name="com.jirbo.adcolony.AdColonyBrowser"
android:configChanges="keyboardHidden|screenSize"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" />
I Have All of the needed codes in Manifest I think
<<<<<<<<<>>>>>>>>>>>
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.google.android.gms:play-services-ads:9.8.0'
compile 'com.google.firebase:firebase-core:9.8.0'
}
apply plugin: 'com.google.gms.google-services'
In Libs, I have "Adcolony *jar"
<<<<<<<<<<< In Java >>>>>>>>>>>>>
import com.jirbo.adcolony.AdColony;
import com.jirbo.adcolony.AdColonyAdapter;
import com.jirbo.adcolony.AdColonyBundleBuilder;
import com.jirbo.adcolony.*;
import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class oyunsonu extends Activity implements RewardedVideoAdListener{
// I Have those implementation with the importations stated above
private static final String AD_UNIT_ID = "xxxxxxxx";
private static final String APP_ID = "xxxxxxxx";
private static final String LOGTAG = "GMS";
private boolean mIsRewardedVideoLoading;
private RewardedVideoAd mRewardedVideoAd2;
private final Object mLock = new Object();
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.oyunsonu);
checkGooglePlayServicesAvailable();
MobileAds.initialize(this, APP_ID);
mRewardedVideoAd2 = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd2.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
private void loadRewardedVideoAd() {
synchronized (mLock) {
if (!mIsRewardedVideoLoading && !mRewardedVideoAd2.isLoaded()) {
mIsRewardedVideoLoading = true;
Bundle extras = new Bundle();
extras.putBoolean("_noRefresh", true);
AdRequest adRequest = new AdRequest.Builder().addNetworkExtrasBundle(AdColonyAdapter.class, extras)
.addNetworkExtrasBundle(AdMobAdapter.class, extras)
.build();
mRewardedVideoAd2.loadAd(AD_UNIT_ID, adRequest);
}
}
}
private void showRewardedVideo() {
if (mRewardedVideoAd2.isLoaded()) {
mRewardedVideoAd2.show();
}
}
private boolean checkGooglePlayServicesAvailable()
{
final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()) ;
if (status == ConnectionResult.SUCCESS)
{
return true;
}
Log.e(LOGTAG, "Google Play Services not available: " + GooglePlayServicesUtil.getErrorString(status));
if (GooglePlayServicesUtil.isUserRecoverableError(status))
{
final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1);
if (errorDialog != null)
{
errorDialog.show();
}
}
return false;
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
mIsRewardedVideoLoading = false;
Toast.makeText(this, "Sunucu Kaynaklı Hata! Ödüllü Reklam Mevcut Değil!", Toast.LENGTH_SHORT).show();
reklamizlex.setVisibility(View.INVISIBLE);
}
#Override
public void onRewardedVideoAdLoaded() {
mIsRewardedVideoLoading = false;
reklamizlex.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewarded(RewardItem reward) {
rekflag = 1;
yenidenoyna.setBackgroundResource(R.drawable.butonbosgri);
anamenuyegit.setBackgroundResource(R.drawable.butonbosgri);
reklamizlex.setBackgroundResource(R.drawable.butonbosgri);
final Intent yenidenoynamakr = new Intent(getApplicationContext(), sorulars.class);
yenidenoynamakr.putExtra("rekdurumu", rekflag);
yenidenoynamakr.putExtra("sonskorx", sonskorz);
yenidenoynamakr.putExtra("katsec", katdurumu);
yenidenoynamakr.putExtra("ajdurumu", ajsay);
yenidenoynamakr.putExtra("yydurumu", yysay);
yenidenoynamakr.putExtra("sdegdurumu", dsay);
yenidenoynamakr.putExtra("ssaydurumu", ssay);
yenidenoynamakr.putExtra("jokkodurumu", jokko);
startActivity(yenidenoynamakr);
}
#Override
public void onRewardedVideoStarted() {
}
}
Here are all codes that I used, which are about the "Rewarded Video Ads"
I could not solve the problem but i think it is caused by AdColony. Because 7 people could manage to see live Ads, the others got the warning as "RewardedVideoFailedtoLoad". I think AdColony limited my Ad views because my App has only 2.500 hit now and also almost 99% exist in Turkey. Probably about the location and download numbers. I've just updated my game with Chartboost.
I am developing and app to Send BLE Advertisement packet in android. I have use AdvertiseData and AdverstiseSettings classes to generate the advertise packet. But when i do the StartAdvertising it always gives me an error with Error Code "2" , "ADVERTISE_FAILED_TOO_MANY_ADVERTISERS", "Failed to start advertising because no advertising instance is available."
Below is my code for MainActivity.JAVA
package rockwellcollins.blutooth_advertise;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothLeScanner mBluetoothLeScanner;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
textView = (TextView) findViewById(R.id.txtv);
mBluetoothLeScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
if( !BluetoothAdapter.getDefaultAdapter().isMultipleAdvertisementSupported() ) {
Toast.makeText(this, "Multiple advertisement not supported", Toast.LENGTH_SHORT).show();
}
advertise();
BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner().startScan(scanCallback);
}
private void advertise() {
BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
AdvertiseSettings settings = new AdvertiseSettings.Builder()
.setAdvertiseMode( AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY )
.setTxPowerLevel( AdvertiseSettings.ADVERTISE_TX_POWER_HIGH )
.setConnectable(false)
.build();
Log.i("BLE","start of advertise data after settings");
ParcelUuid pUuid = new ParcelUuid( UUID.fromString("b161c53c-0715-11e6-b512-3e1d05defe78"));
AdvertiseData data = new AdvertiseData.Builder()
.setIncludeDeviceName( true )
.setIncludeTxPowerLevel(true)
.addServiceUuid( pUuid )
//.addServiceData( pUuid, "Data".getBytes(Charset.forName("UTF-8") ) )
.build();
Log.i("BLE","before callback");
AdvertiseCallback advertisingCallback = new AdvertiseCallback() {
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
Log.i("BLE", "LE Advertise success.");
}
#Override
public void onStartFailure(int errorCode) {
Log.e("BLE", "Advertising onStartFailure: " + errorCode);
super.onStartFailure(errorCode);
}
};
advertiser.startAdvertising( settings, data, advertisingCallback );
Log.i("BLE", "start advertising");
}
private final ScanCallback scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
printScanResult(result);
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
textView.append("Received " + results.size() + " batch results:\n");
for (ScanResult r : results) {
printScanResult(r);
}
}
#Override
public void onScanFailed(int errorCode) {
switch (errorCode) {
case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
textView.append("Scan failed: already started.\n");
break;
case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
textView.append("Scan failed: app registration failed.\n");
break;
case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
textView.append("Scan failed: feature unsupported.\n");
break;
case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
textView.append("Scan failed: internal error.\n");
break;
}
}
private void printScanResult(ScanResult result) {
String id = result.getDevice() != null ? result.getDevice().getAddress() : "unknown";
int tx = result.getScanRecord() != null ? result.getScanRecord().getTxPowerLevel() : 0;
textView.append("TX: " + tx + " RX: " + result.getRssi() + " from " + id+ ".\n");
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Code for Android Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="rockwellcollins.blutooth_advertise">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Could you please let me know what I am doing wrong and how can I solve this error?
Thanks
From my experience there are 4 types of Android devices in regard BLE advertisement:
Devices with Android pre-5.0 - LE Advertisement not supported
Devices with Android 5+ that don't support LE Advertisement and return null from getBluetoothLeAdvertiser(). Those devices return false from isMultipleAdvertisementSupported(). They do this even with Bluetooth ON (see Note below).
Devices with Android 5+ that return the BluetoothLeAdvertiser object, but each try of advertising ends with ADVERTISE_FAILED_TOO_MANY_ADVERTISERS error (this is the case you have). Those devices return true from isMultipleAdvertisementSupported() which as you see is not true. So far I've seen only one phone from this category: Sony xperia z1 compact, but if there is one, there are more.
Devices with Android 5+ that support LE Advertisement. Those return true from isMultipleAdvertisementSupported() but ONLY when Bluetooth is ON.
Note: in the 2., 3. and 4. the BluetoothLeAdvertiser object is returned ONLY when Bluetooth is ON. Otherwise null is returned, so you actually have no clue whether the device supports LE Advertisement or not until Bluetooth is enabled.
Check the nRF Connect app: Disable Bluetooth, install the app, open and select Advertiser tab or Navigation menu -> Device information. It will ask you to turn Bluetooth ON before the status will be shown.
See this question for a possible answer, BLE Advertisments are not supported on every device.
Also try to omit the device name as suggested here.
You only need to add this code: #TargetApi(Build.VERSION_CODES.M) over your method
package blessupboys.speechtest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.util.Log;
public class VoiceRecognitionTest extends Activity implements OnClickListener
{
private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyStt3Activity";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_recognition_test);
Button speakButton = (Button) findViewById(R.id.btn_speak);
mText = (TextView) findViewById(R.id.textView1);
speakButton.setOnClickListener(this);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
mText.setText("error " + error);
}
public void onResults(Bundle results)
{
String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
mText.setText("results: "+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.btn_speak)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
}
}
}
And My Android Manifest File looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="blessupboys.speechtest">
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".VoiceRecognitionTest"
android:label="#string/title_activity_voice_recognition_test"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
My logs show that it stops because of error 9 generated in the onError() function.
01-19 20:04:57.776 18480-18480/? I/art: Not late-enabling -Xcheck:jni (already on)
01-19 20:04:57.925 18480-18480/blessupboys.speechtest W/System: ClassLoader referenced unknown path: /data/app/blessupboys.speechtest-2/lib/x86
01-19 20:04:58.341 18480-18515/blessupboys.speechtest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-19 20:04:58.443 18480-18515/blessupboys.speechtest I/OpenGLRenderer: Initialized EGL, version 1.4
01-19 20:04:58.497 18480-18515/blessupboys.speechtest W/EGL_emulation: eglSurfaceAttrib not implemented
01-19 20:04:58.497 18480-18515/blessupboys.speechtest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad79f260, error=EGL_SUCCESS
01-19 20:04:59.033 18480-18480/blessupboys.speechtest I/Choreographer: Skipped 39 frames! The application may be doing too much work on its main thread.
01-19 20:10:09.965 18480-18480/blessupboys.speechtest I/111111: 11111111
01-19 20:10:10.049 18480-18480/blessupboys.speechtest D/MyStt3Activity: error 9
I am trying to run this sample program to try to get familiar with the Speech Recognizer software..
Could this be an issue being caused by the fact that I'm running it on android studio rather than a real device? I am pretty stuck on this.
In case anyone comes to this question and none of the other answers help, you might want to try requesting permissions using the following code:
private void requestRecordAudioPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String requiredPermission = Manifest.permission.RECORD_AUDIO;
// If the user previously denied this permission then show a message explaining why
// this permission is needed
if (checkCallingOrSelfPermission(requiredPermission) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{requiredPermission}, 101);
}
}
}
Error 9 ERROR_INSUFFICIENT_PERMISSIONS is also thrown when google does not have record_audio permission.
Check the Settings -> Apps -> Google -> Permissions -> Microphone
It was just a problem with it not being supported on emulators. It works on a physical device.
What I found is that if you are "just a physical device" and you still get the same error, that is most probably is because if the target SDK in the gradle file. you see in later versions they have changed the level of permission to dangers, so by downgrading it, then you it will work.
"I am not an expert in this, but this worked from me fine"
try these links for references to your project also check all android manifest permissions here and here is a sample project
hope these hints help to solve your problem!
I am using AndroidIbeacon library released by radiusnetworks and I am able to run their demo app successfully. But when I add that to my application onIBeaconServiceConnect() method is not called.
Below my code,
public class Sample extends Activity implements IBeaconConsumer {
protected static final String TAG = "Sample";
private IBeaconManager iBeaconManager = IBeaconManager
.getInstanceForApplication(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
iBeaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
iBeaconManager.unBind(this);
}
#Override
public void onIBeaconServiceConnect() {
iBeaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.i(TAG, "I just saw an iBeacon for the firt time!");
}
#Override
public void didExitRegion(Region region) {
Log.i(TAG, "I no longer see an iBeacon");
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
Log.i(TAG,
"I have just switched from seeing/not seeing iBeacons: "
+ state);
}
});
try {
iBeaconManager.startMonitoringBeaconsInRegion(new Region(
"myMonitoringUniqueId", null, null, null));
} catch (RemoteException e) {
}
}
}
Kindly help me to solve this issue. thanks
If manifest merging does not work, try this (worked for me):
Add the following service declarations to your AnroidManifest.xml, replacing {my app's package name} with the fully qualified package name of your Android application.
<service android:enabled="true"
android:exported="true"
android:isolatedProcess="false"
android:label="iBeacon"
android:name="com.radiusnetworks.ibeacon.service.IBeaconService">
</service>
<service android:enabled="true"
android:name="com.radiusnetworks.ibeacon.IBeaconIntentProcessor">
<meta-data android:name="background" android:value="true" />
<intent-filter
android:priority="1" >
<action android:name="{my app's package name}.DID_RANGING" />
<action android:name="{my app's package name}.DID_MONITORING" />
</intent-filter>
</service>
The most common cause of this issue is that the proper entries to start the library's service are not in the project AndroudManifest.xml file. Your new project must pull in these entries from the library's manifest using a feature called manifest merging.
Make sure you have followed the setup instructions here. If using Eclipse, verify your project.properties has manifestmerger.enabled=true.
adding
manifestmerger.enabled=true
in project.properties worked for me!
Source