Hello I am making a bluetooth connecting android app.
I followed the instruction from developer.android.com
while I am testing my app, I look forward to it works properly, but it didn't.
I tried to get detected BLE devices names, but don't know the reason why it doesn't show me the devices name...
Arduino nano 33 IOT is adverstising bluetooth next to my android phone, and I am trying to detect it and get the Adrduino's BLE device name and address.
here is my MainActivity.java
public class MainActivity extends AppCompatActivity {
//View Contents Elements
public Button btnActivateBluetooth;
public Button btnSearchBluetooth;
public Button btnSendData;
public ListView lvSearchedDevice;
public ListView lvLog;
public TextView tvStatus;
public EditText etData;
//etc values
public ArrayAdapter<String> logAdapter;
private final int REQUEST_ENABLE_BT = 1;
private boolean mScanning = true;
//bluetooth values
public BluetoothAdapter btAdapter;
public BluetoothManager btManager;
private Handler handler;
#SuppressLint("MissingPermission")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//View Elements
btnSearchBluetooth = (Button) findViewById(R.id.btnSearchBluetooth);
btnSendData = (Button) findViewById(R.id.btnSendData);
lvSearchedDevice = (ListView) findViewById(R.id.lvSearchedDevice);
lvLog = (ListView) findViewById(R.id.log);
tvStatus = (TextView) findViewById(R.id.tvStatus);
etData = (EditText) findViewById(R.id.etData);
//etc
logAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lvLog.setAdapter(logAdapter);
handler = new Handler();
// Initializes Bluetooth adapter.
btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
// displays a dialog requesting user permission to enable Bluetooth.
if (btAdapter == null || !btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
btnSearchBluetooth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanLeDevice(true);
}
});
}
//Scan devices
#SuppressLint("MissingPermission")
private void scanLeDevice(final boolean enable){
if(enable){
handler.postDelayed(new Runnable() {
#SuppressLint("MissingPermission")
#Override
public void run() {
btAdapter.stopLeScan(leScanCallback);
}
},5000);
btAdapter.startLeScan(leScanCallback);
}
else
{
btAdapter.stopLeScan(leScanCallback);
}
}
//Callback method
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#SuppressLint("MissingPermission")
#Override
public void run() {
Toast.makeText(MainActivity.this, device.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
}
and this is my Arduino nano 33 IOT's code.
#include <ArduinoBLE.h>
BLEService Toothbrush("00001101-0000-1000-8000-00805F9B34FB");
BLEStringCharacteristic ToothbrushChar("00001101-0000-1000-8000-00805F9B34FB",BLEWrite|BLERead | BLENotify, 10);
void setup() {
Serial.begin(9600);
if(!BLE.begin()){
Serial.println("Starting BLE failed.");
while(1);
}
BLE.setLocalName("HayanToothbrush");
BLE.setAdvertisedService(Toothbrush);
Toothbrush.addCharacteristic(ToothbrushChar);
BLE.addService(Toothbrush);
BLE.advertise();
Serial.println("Bluetooth device active, wating for connections...");
}
void loop() {
BLEDevice central = BLE.central();
if(central) {
Serial.print("Connected to central : ");
Serial.println(central.address());
while(central.connected()){
}
Serial.print("Disconnected from central:");
Serial.println(central.address());
}
}
I add permissions in the Mainfest as below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.bluetooth0523">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Bluetooth0523"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
But it still doesn't find me scanned device name.
I think it's on LeScanCallBack problem.
When running startLeScan, It seems not running callback method.
in addition, I am running this app on SDK_VERSION_30
and Arduino nano IOT 33 is discoverable If I use the Bluetooth function that my phone has, not my application, it will be displayed in the scan result list.
I want to get scan result on my own app.
but don't know where is the problem.
Permissions must be declared and requested depending on Android version. Main differences are:
Target Android 12 or higher
BLUETOOTH_SCAN
Target Android 11 or lower
ACCESS_FINE_LOCATION
See Bluetooth permissions for details.
Related
I am still new to Android development, but I’m creating an app that sendings an HTTP request when it receives a broadcast (from a barcode scan). I have tried to implement some other solutions that I read on here but haven't quite figured it out yet. It would be great if someone could help me get going in the right direction.
Essentially, the end goal is for the app to keep running in the background forever so that even if the app is not open and a barcode is scanned and sent to the app via broadcast signal, the HTTP request is still sent.
This is what I have so far:
MainActivity.java
public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
public static final String BARCODE_BROADCAST = "...";
private final BarcodeReceiver barcodeReceiver = new BarcodeReceiver();
private TextView mTextView;
private String scannedBarcode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.barcode);
}
#Override
public void onResume() {
super.onResume();
registerBarcodeScanner();
}
#Override
public void onPause() {
super.onPause();
unregisterBarcodeScanner();
// this code needs to keep the app running
Intent restartService = new Intent("RestartService");
this.startService(restartService);
sendBroadcast(restartService);
}
public void onDestroy() {
super.onDestroy();
// this code needs to keep the app running
Intent restartService = new Intent("RestartService");
this.startService(restartService);
sendBroadcast(restartService);
}
private void registerBarcodeScanner() {
registerReceiver(barcodeReceiver, new IntentFilter(BARCODE_BROADCAST));
}
private void unregisterBarcodeScanner() {
unregisterReceiver(barcodeReceiver);
}
private void displayBarcode() {
if (scannedBarcode == null) return;
String text = getString(R.string.barcode_scanned, scannedBarcode);
mTextView.setText(text);
/* SEND HTTP REQUEST */
}
private class BarcodeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BARCODE_BROADCAST)) {
String barcode = intent.getStringExtra("Barcode");
if (barcode != null) {
scannedBarcode = barcode;
displayBarcode();
}
}
}
}
}
RestartService.java
public class RestartService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MainActivity.class));
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="..."
android:versionCode="1">
<uses-sdk android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
tools:replace="android:label">
<activity
android:name="...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>
<receiver
android:name="...RestartService"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="RestartService" />
</intent-filter>
</receiver>
</application>
</manifest>
I have a problem with my Android Studio app using Google Maps, the problem being that my map doesn't completely load. I do get the fully loaded world map, but that's as far as it goes.
The functionality of the app itself works great, I am able to type in whatever country/city/address that I want, and stick a marker to that location (Which in my simple mind tells me that I have all the permissions that I require to utilize the functions I want for this application).
I have been browsing for solutions for hours, but everything I have found, I already have enabled and/or working. I use my Samsung Galaxy S7 phone to run my app and have had no problems so far with Android Studio.
I guess this is just a "cosmetic" issue, but still one I would like to solve.
What I have tried:
Clearing the cache on my device of, Google Play Services, Google Play Store
Getting new API keys from google
Different map layouts MAP_TYPE_NORMAL, MAP_TYPE_HYBRID <- The hyrbid layout does not load at all.
My internet connection, Wifi/Wireless (I have a fast internet connection using either, I doubt that's the problem)
Pictures to better describe what happens:
Starting the app with custom markers.
Zooming in.
Final zoom, with markers in the correct spot.
My code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
EditText searchText;
public GoogleMap mMap;
private static final float DEFAULT_ZOOM = 15.0f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
try {
if (mMap == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
searchText = (EditText) findViewById(R.id.input_search);
init();
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
}
//init the search
public void init()
{
searchText.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE)
{
geoLocate();
}
return false;
}
});
}
private void geoLocate()
{
String searchString = searchText.getText().toString();
Geocoder geocoder = new Geocoder(MapsActivity.this);
List<Address> list = new ArrayList<>();
try
{
list = geocoder.getFromLocationName(searchString, 1);
}
catch(Exception e)
{
e.printStackTrace();
}
if(list.size() > 0)
{
Address address = list.get(0);
LatLng position = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title(searchText.getText().toString()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, DEFAULT_ZOOM));
}
}
}
My AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!--android:value="#string/google_maps_key" />-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="*Api*" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My google_maps_api.xml file:
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">*Api*</string>
</resources>
I obviously discluded the API_KEY's with Api.
This is my first post on stackoverflow so any feedback regarding the quality of my post is welcome as well.
Can you confirm that you have setup you Android Google Maps SDK API Key in the google developer console, If not then please Enable Google Maps Android API in google developer console with your application identifier and SHA1 fingerprint? The map won't show until the key is authorised for the particular debug/production build of your app.
I'm trying to read USSD response to get Sim balance amount etc, and I'm having issues, I have been reading many questions related to that on Stackoverflow, nothing has worked so far. Except for this that came close: Prevent USSD dialog and read USSD response?. by #HenBoy331
But i'm still having issues with it. My broadcast receiver doesn't get called too. I'm using 4.4.2
But it shows nothing. I can't seem to parse the message and get the balance.
I have a MainActivity to make the phone call, ReceiverActivity to implement broadcast receiver, USSDService class to get the USSD response.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, USSDService.class));
dailNumber("100");
}
private void dailNumber(String code) {
String ussdCode = "*" + code + Uri.encode("#");
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussdCode)));
}
}
RecieverActivity.java
public class RecieverActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter("com.times.ussd.action.REFRESH");
this.registerReceiver(new Receiver(), filter);
}
public class Receiver extends BroadcastReceiver {
private String TAG = "XXXX";
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.i(TAG, "Got message: " + message);
}
}
}
USSDService.java
public class USSDService extends AccessibilityService {
public String TAG = "XXXX";
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.d(TAG, "onAccessibilityEvent");
AccessibilityNodeInfo source = event.getSource();
/* if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !event.getClassName().equals("android.app.AlertDialog")) { // android.app.AlertDialog is the standard but not for all phones */
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !String.valueOf(event.getClassName()).contains("AlertDialog")) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && (source == null || !source.getClassName().equals("android.widget.TextView"))) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && TextUtils.isEmpty(source.getText())) {
return;
}
List<CharSequence> eventText;
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
eventText = event.getText();
} else {
eventText = Collections.singletonList(source.getText());
}
String text = processUSSDText(eventText);
if( TextUtils.isEmpty(text) ) return;
// Close dialog
performGlobalAction(GLOBAL_ACTION_BACK); // This works on 4.1+ only
Log.d(TAG, text);
// Handle USSD response here
Intent intent = new Intent("com.times.ussd.action.REFRESH");
intent.putExtra("message", text);
sendBroadcast(intent);
}
private String processUSSDText(List<CharSequence> eventText) {
for (CharSequence s : eventText) {
String text = String.valueOf(s);
// Return text if text is the expected ussd response
if( true ) {
return text;
}
}
return null;
}
#Override
public void onInterrupt() {
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.flags = AccessibilityServiceInfo.DEFAULT;
info.packageNames = new String[]{"com.android.phone"};
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
setServiceInfo(info);
}
}
AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dialussd">
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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>
<service
android:name=".services.USSDService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="#xml/config_service" />
</service>
<receiver android:name=".RecieverActivity$Receiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Please, is there any way i'm implementing this wrongly, Or perhaps there is a new way to get USSD responses which works?
After the launch, change the settings manually
Setting->Accessibility Setting -> You can see a option 'your app name'. Turn it on. (This has to be done from as a part of application flow(not manual))
instead of using broadcast receiver use these two lines of code in
add this code in MainActivity
public static void setTextViewToModify(String Text) {
textView.setText(Text);}
and add this in service class with in onAccessibityEvent
MainActivity.setTextViewToModify(text);
I am currently working on a music tuner that uses html5 and a webview to display the 'application'. I've written the all the permission required in manifest and I think for webview there's another permission required.
I am using this https://jbergknoff.github.io/guitar-tuner/ as a sample redirect page for now
Here's my manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.raynordev.projectrosin">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MICROPHONE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.audio.low_latency" />
<uses-feature android:name="android.hardware.audio.pro" />
<uses-feature android:name="android.hardware.microphone" android:required="true"/>
<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:theme="#style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.raynordev.projectrosin.HomeActivity">
</activity>
</application>
</manifest>
Here's my .java
public class HomeActivity extends AppCompatActivity {
private WebView wv;
private String TAG = "HomeActivity";
private static final int REQUEST_INTERNET = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebView wv = (WebView) findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.setWebViewClient(new WebViewClient());
wv.setWebChromeClient(new WebChromeClient());
wv.loadUrl("https://jbergknoff.github.io/guitar-tuner/");
}
}
If require more information from me, please let me know.
Thank you everyone!!
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Example:
MainActivity
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 101;
private ActivityMainBinding mBinding;
private PermissionRequest myRequest;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setWebView();
}
private void setWebView() {
mBinding.webView.getSettings().setJavaScriptEnabled(true);
mBinding.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mBinding.webView.setWebViewClient(new WebViewClient());
mBinding.webView.getSettings().setSaveFormData(true);
mBinding.webView.getSettings().setSupportZoom(false);
mBinding.webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mBinding.webViemBinding.webView.getSettings().setPluginState(WebSettings.PluginState.ON);
mBinding.webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onPermissionRequest(final PermissionRequest request) {
myRequest = request;
for (String permission : request.getResources()) {
switch (permission) {
case "android.webkit.resource.AUDIO_CAPTURE": {
askForPermission(request.getOrigin().toString(), Manifest.permission.RECORD_AUDIO, MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
break;
}
}
}
}
});
mBinding.webView.loadUrl("<your url");
}
#Override
public void onBackPressed() {
if (mBinding.webView.canGoBack()) {
mBinding.webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_RECORD_AUDIO: {
Log.d("WebView", "PERMISSION FOR AUDIO");
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
myRequest.grant(myRequest.getResources());
mBinding.webView.loadUrl("<your url>");
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void askForPermission(String origin, String permission, int requestCode) {
Log.d("WebView", "inside askForPermission for" + origin + "with" + permission);
if (ContextCompat.checkSelfPermission(getApplicationContext(),
permission)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
permission)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{permission},
requestCode);
}
} else {
myRequest.grant(myRequest.getResources());
}
}
}
Mainfest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MICROPHONE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.audio.low_latency" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-feature android:name="android.hardware.audio.pro" />
<uses-feature android:name="android.hardware.microphone"/>
Build.gradle:
android {
compileSdkVersion 26
defaultConfig {
applicationId "myapp.example.com.myapplication"
minSdkVersion 21
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
Summarising, you need the following components:
The MODIFY_AUDIO_SETTINGS permission.
A WebChromeClient and listen to callbacks for onPermissionRequest
Inside this callback, check for the the resources coming in the request object, create a global variable of this request object, iterate and look for specific permission inside the PermissionRequest class, ex. PermissionRequest.RESOURCE_VIDEO_CAPTURE which translates to the Manifest.permission.CAMERA permission, check if your app has this permission or not, using any mechanism you wish if not, request, if yes do 4.
In the permission callback or if the permission is granted, use the request object to grant the permission ex. request.grant(new String[]{PermissionRequest.RESOURCE_VIDEO_CAPTURE}) and you're good to go.
snippet:
webView.webChromeClient = object: WebChromeClient(){
override fun onPermissionRequest(request: PermissionRequest?) {
super.onPermissionRequest(request)
webkitPermissionRequest = request
request?.resources?.forEach {
when(it){
PermissionRequest.RESOURCE_AUDIO_CAPTURE-> {
askForWebkitPermission(it, Manifest.permission.RECORD_AUDIO, REQUEST_CODE_PERMISSION_AUDIO)
}
PermissionRequest.RESOURCE_VIDEO_CAPTURE->{
askForWebkitPermission(it, Manifest.permission.CAMERA, REQUEST_CODE_PERMISSION_CAMERA)
}
}
}
}
}
private fun askForWebkitPermission(webkitPermission: String, androidPermission: String, requestCode: Int){
val context = activity?: return
if (context.hasPermission(androidPermission)){
webkitPermissionRequest!!.grant(arrayOf(webkitPermission))
}else{
requestPermissions(arrayOf(androidPermission), requestCode)
}
}
Hope this helps.
Google's sample for the same: https://github.com/googlesamples/android-PermissionRequest
its problems for reload the webview , after too much research , found this code and create this below code :-
mwebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onPermissionRequest(final PermissionRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
myRequest = request;
for (String permission : request.getResources()) {
if (permission.equals("android.webkit.resource.AUDIO_CAPTURE")) {
demandForPermission(request.getOrigin().toString(), Manifest.permission.RECORD_AUDIO, MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
} else {
myRequest.grant(request.getResources());
}
}
}
}
#Override
public void onPermissionRequestCanceled(PermissionRequest request) {
super.onPermissionRequestCanceled(request);
}
more info in this link Android Webview
I have my main activity that start a service (Location service) and I want that service to broadcast the new location each time a new location is found.
Thanks to the log I know the service is working and I have new locations every seconds or so, but I never get the broadcast.
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = "mainActivity";
private CMBroadcastReceiver mMessageReceiver = new CMBroadcastReceiver();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// Start Service
startService(new Intent(this, LocationService.class));
super.onCreate(savedInstanceState);
}
#Override
public void onResume()
{
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE));
super.onResume();
}
#Override
public void onPause()
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
}
CMBroadcastReceiver.java
public class CMBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CMBroadcastReceiver";
public static final String RECEIVE_LOCATION_UPDATE = "LOCATION_UPDATES";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received broadcast");
String action = intent.getAction();
if (action.equals(RECEIVE_LOCATION_UPDATE))
{
Log.i(TAG, "Received location update from service!");
}
}
}
LocationService.java
/**
* Callback that fires when the location changes.
*/
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i(TAG, "onLocationChanged " + location);
Intent intent = new Intent(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.i(TAG, "Broadcast sent");
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyclemapapp.gpstracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<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/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".LocationService" android:process=":location_service" />
</application>
I the log I can see that "Broadcast Sent" But I never get the "Broadcast Received"
Any help will would be greatly appreciated.
EDIT:
Edited how the intent was created in the location service as Shaishav suggested.
Still doesn't work.
LocalBroadcastManager does not work across processes. Your Service is running in a separate process.
You can either run your Service in the same process as the Activity - by removing the process attribute from the <service> element - or use some sort of IPC instead - e.g., by sending and receiving the broadcasts on a Context instead of LocalBroadcastManager.
In your LocationService, send local broadcast using:
Intent intent = new Intent(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
<service android:name=".LocationService" android:process=":location_service" />
Your service is in a separate process from the activity. LocalBroadcastManager is only for use in one process. Either remove android:process from the <service>, or use some IPC mechanism (e.g., system broadcasts, properly secured).