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
Related
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 want to send a BLE advertisement using Android beacon library. Below is the code I am using for it.
package com.example.beacon_emitter;
import java.util.Arrays;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.BeaconTransmitter;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseSettings;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Beacon beacon = new Beacon.Builder()
.setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
.setId2("1")
.setId3("2")
.setManufacturer(0x0118)
.setTxPower(-59)
.setDataFields(Arrays.asList(new Long[] {0l}))
.build();
BeaconParser beaconParser = new BeaconParser()
.setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getApplicationContext(), beaconParser);
beaconTransmitter.startAdvertising(beacon,new AdvertiseCallback() {
#Override
public void onStartFailure(int errorCode) {
Log.e("beacon", "Advertisement start failed with code: "+errorCode);
}
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
Log.i("beacon", "Advertisement start succeeded.");
}
});
int result = BeaconTransmitter.checkTransmissionSupported(getApplicationContext());
Toast.makeText(this, "Device info " + result, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It always gives me an errorcode 2, ADVERTISE_FAILED_TOO_MANY_ADVERTISERS. But the strange thing is when I checked the toast message it says the my device is supported the beacon transmission. I am confused.
Please help!
Thanks in Advance.
A few tips:
The BeaconTransmitter.checkTransmissionSupported() method only checks to see if the device has Bluetooth LE and that the operating system will give you a BluetoothAdvertiser.
To see if somebody else has been successful with getting your device to transmit, check to see if it is on this list: http://altbeacon.github.io/android-beacon-library/beacon-transmitter-devices.html
The ADVERTISE_FAILED_TOO_MANY_ADVERTISERS response can indicate that another app is advertising a beacon, and all the advertisement slots are used. Make sure that you don't have any other apps advertising in the background. Reboot or uninstall other apps that might be doing this if necessary.
Try the Locate Beacon app which is based on this same library, and see if it can advertise a beacon successfully. This will eliminate any possible problem with your code.
EDIT: Based on the comments below, it is reasonable to conclude that the firmware for the Intrynsyc eval kit does not properly implement the interface between Android and the Bluetooth chip. Otherwise it would either report that advertising is not available or it would not return an error message when starting advertising. The appropriate next step would be to open an issue with Intrynsyc and report these findings.
The ability to transmit as a beacon requires Bluetooth LE
advertisement capability, which may or may not be supported by a
device’s firmware.
Quote from Device Support For Beacon Transmission with Android 5+
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'm trying to run a server on a Android device using the JLAN library.
After some works, it seems running, stopping.
From an other Android device, I can connect and see my share folder by adding manually a server with smb://192.168.0.10:1445.
Here my problems:
1) I rooted the Android Device but I can't use the port above 1024. (So I use 1445 instead 445)
2) From any other device, I can't see automaticaly my server.
It seems my netbios or my broadcast configuration is incorrect.
3) I tried connect it from a MAC like a "anonym" with smb://192.168.0.10:1445.
The authentication windows appears but when I confirm MAC said that I have no the right or that there is not any share folder.
Code of my files:
My Xml configuration file:
<?xml version="1.0" standalone="no"?>
<jlanserver>
<servers>
<SMB/>
<noFTP/>
<noNFS/>
</servers>
<SMB>
<host name="serveur" domain="Workgroup">
<broadcast>255.255.0.0</broadcast>
<smbdialects>Core,LanMan,NT</smbdialects>
<netBIOSSMB sessionPort="1139" namePort="1137" datagramPort="1138" platforms="linux,solaris,macosx,windows"/>
<tcpipSMB platforms = "linux,macosx,windows,solaris" port = "1445"/>
<comment>SMB Android Server</comment>
</host>
<authenticator type="local">
<class>org.alfresco.jlan.server.auth.LocalAuthenticator</class>
<mode>USER</mode>
<Debug/>
<allowGuest/>
</authenticator>
<!-- Debug -->
<sessionDebug flags="Netbios,State,Negotiate,Tree,Transact,Echo"/>
<netbiosDebug/>
<announceDebug/>
</SMB>
<shares>
<diskshare name="ESPACE" comment="Dossier de Partage">
<driver>
<class>org.alfresco.jlan.smb.server.disk.JavaFileDiskDriver</class>
<LocalPath>/tmp</LocalPath>
</driver>
<size totalSize="2T" freeSize="100G"/>-->
<accessControl default="Write"/>
</diskshare>
</shares>
<security>
<authenticator type="local">
<class>org.alfresco.jlan.server.auth.LocalAuthenticator</class>
<mode>USER</mode>
<Debug/>
<allowGuest/>
</authenticator>
</security>
<shareMapper>
<class>org.alfresco.jlan.smb.server.DefaultShareMapper</class>
<debug/>
</shareMapper>
My Main Class:
(Launchserver and StopServer are called clicking buttons in my activity)
package archisoft.com.smbserverandroid;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.alfresco.jlan.app.XMLServerConfiguration;
import org.alfresco.jlan.smb.server.CIFSConfigSection;
import org.alfresco.jlan.smb.server.SMBServer;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Configuration extends ActionBarActivity {
public static final String TAG = "ServiceServerSMB";
private Button stopButton = null;
private Button startButton = null;
private XMLServerConfiguration srvConfig;
SMBServer MonServer;
// A la création
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "####### onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
}
// Au redémarrage
#Override
public void onStart()
{
Log.d(TAG, "####### onStart");
super.onStart();
// On bind les boutons
startButton = (Button) findViewById(R.id.buttonStart);
stopButton = (Button) findViewById(R.id.buttonStop);
}
// Au retour sur l'activité
#Override
public void onResume()
{
Log.d(TAG, "####### onResume");
super.onResume();
}
// A l'arrêt
#Override
public void onStop()
{
Log.d(TAG, "####### onStop");
super.onStop();
}
#Override
public void onPause()
{
Log.d(TAG, "####### onPause");
super.onPause();
}
// Destruction
#Override
public void onDestroy() {
Log.d(TAG, "####### Destruction");
super.onDestroy();
}
// Appelé lorsque l'on clique sur "Start Server"
public void LaunchServer(View view)
{
Log.d(TAG, "####### Launch server");
try {
InputStream stream = getResources().openRawResource(R.raw.jlanconfiguration);
srvConfig = new XMLServerConfiguration();
srvConfig.loadConfiguration(new InputStreamReader(stream));
((CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName)).setDatagramPort(1138);
((CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName)).setNameServerPort(1137);
((CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName)).setSessionPort(1139);
CIFSConfigSection cifsConfig = (CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName);
MonServer = new SMBServer(srvConfig);
MonServer.startServer();
Log.d(TAG, "Lancement serveur");
} catch (Exception e) {
Log.e(TAG, "Erreur lancement serveur", e);
}
}
public void StopServer(View view)
{
Log.d(TAG, "####### StopServer");
MonServer.shutdownServer(true);
}
}
Thanks for all people who will try to help me.
Any advice would be welcome.
If you have any question, feel free to ask.
Best regards!
Anthony
You can see the shared folder in PC from android mobile by using jcifs which is cool please try this link pass your username and password and u can get all the shared folders by just one step smbFile.listfiles(). try it it worked for me.
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