I'm trying to start the bluetooth sco to be able to record a call through bluetooth headset but every tim i execute the code , it returns disconencted even though bluetooth is on and headsets are connected , any reason why Thank you .
Manifest File
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />
Registering receiver
// register new receiver for bluetooth headset
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); // API 14
registerReceiver(broadcastReceiver,intentFilter);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.startBluetoothSco();
if(audioManager.isBluetoothScoOn()){
Log.d("TAG","True");
} else {
Log.d("TAG","False");
}
Receiver code
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,-1);
if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
// Start recording audio
isConnected = true;
Log.d("TAG","audio connected");
} else if(state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED){
Log.d("TAG","audio Disconnected");
} else if (state == AudioManager.SCO_AUDIO_STATE_CONNECTING){
Log.d("TAG","audio Connecting");
}
}
};
LOGS
Related
Hello i have followed the example in https://developer.android.com/guide/topics/connectivity/bluetooth and my broadcast receiver maybe is not working. I am running android 8.1 in my Android Xiaomi mi A1 device.
#Override
protected void onCreate(Bundle savedInstanceState) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
bluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Toast.makeText(MainActivity.this, deviceName, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, deviceHardwareAddress, Toast.LENGTH_SHORT).show();
mDeviceList.add(deviceHardwareAddress);
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,mDeviceList);
listV.setAdapter(arrayAdapter);
}
}
};
Thank you!
NOTE
For android Api 21 Broadcast receiver works fine is there a change i have to make to make it work for Android 8.1?
In manifest I have put the permissions and other services like start stop bluetooth and find paired devices are working fine...
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
You Need to Add Permission in code above Version M
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
I have problem with specific device REDMI 6A (with OS MIUI Android Oreo 8.1), according to my project. it's simple application, only connect to the server trigger by BOOT_COMPLETED event. i try to check the internet connection is connected or not. it is really weird the Redmi 6A can't connect,but when i test with MI A1 (OS Android Oreo 8.1 - Android One) the device can connect as well. I really don't understand why this can be happen. I really appreciate if some one can advice me.
This Below the code.
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.NETWORK" />
....................
<service
android:name=".services.SocketJobIntentService"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" android:label="#string/socket_job" />
<receiver
android:name=".broadcast.MainBroadCastReceiver"
android:enabled="true"
android:label="#string/receiver_name">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".services.SocketSvc"></service>
SocketJobIntentService.java
public class SocketJobIntentService extends JobIntentService {
static Context context;
static final int JOB_ID = 1000;
public static void enqueueWork(Context _context, Intent work) {
context = _context;
enqueueWork(_context, SocketJobIntentService.class, JOB_ID, work);
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
if(context==null){context = this;}
boolean isInternetConnected = isOnline(context);
if(isInternetConnected) {
Log.d("DT_JobIntentService","Executed!! and try to Calling Another Service 'SocketSvc' !!!");
Intent service = new Intent(this,SocketSvc.class);
startService(service);
}else{
Log.e("DT_WeGetEcon","isInternetConnected=false !!!!!! LOL!");
}
}}
MainBroadCastReceiver.java
public class MainBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
try {
String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
Log.d("DT_MainBroadCastRceiver", action+" Called !!!");
SocketJobIntentService.enqueueWork(context, new Intent());
Log.d("DT_JobIntent","Try to call JobIntent");
}
}
catch (Exception exc){
Log.e("DT_ERR_ACTBOOT_COMPLTED",exc.getMessage());
}
}}
LogCat
LogCat MI A1
LogCat RedMI 6A
I really appreciate if anyone can advice me.
Thanks
Finally, I found my own solution.
Just put two line code inside onReceive MainBroadCastReceiver.java
public void onReceive(final Context context, Intent intent) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ref to : Error StrictMode$AndroidBlockGuardPolicy.onNetwork
I wanted to make this service a never ending service, even if the app is killed by the user. That service starts with the app - when it is background, the service still runs-, but when I clear the background tasks on phone, it is also killed. I wanted that final part to be different, wanted this service to keep running on the device... Is that possible? Thanks for the help
public class BackgroundService extends Service {
public static Runnable runnable = null;
public Context context = this;
public Handler handler = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
final PackageManager manager = getPackageManager();
//Packages instalados no dispositivo
List<ApplicationInfo> packages = manager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo info : packages) {
Log.i("Info", "Installed package:" + info.packageName);
}
for (int i = 0; i < packages.size(); i++) {
if(packages.get(i).sourceDir.startsWith("/data/app/")){
//Non System Apps
Log.i("Info", "Installed package /NON SYSTEM/:" + packages.get(i).packageName);
}else{
//system Apps
Log.i("Info", "Installed package !/SYSTEM/!:" + packages.get(i).packageName);
}}
handler = new Handler();
runnable = new Runnable() {
public void run() {
final ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
String currentApp ="";
// The first in the list of RunningTasks is always the foreground task.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(),
usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(
mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
currentApp = foregroundTaskInfo.topActivity.getPackageName();
}
boolean ApiLigaIsRunning = false;
if (currentApp.contains("maps")) {
ApiLigaIsRunning = true;
Log.i("CHOOSEN APP IS RUNNING ","YES!!!!!!!!!!! " + currentApp);
Handler handler2 = new Handler();
final String finalCurrentApp = currentApp;
handler2.postDelayed(new Runnable() {
public void run() {
Intent openMe = new Intent(getApplicationContext(), LoginActivity.class);
openMe.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(openMe);
am.killBackgroundProcesses(finalCurrentApp);
}
}, 200);
}
Toast.makeText(context, "Service is running", Toast.LENGTH_LONG).show();
List<ActivityManager.RunningAppProcessInfo> appProcesses = am.getRunningAppProcesses();
for(ActivityManager.RunningAppProcessInfo appProcess : appProcesses){
if(appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
if (ApiLigaIsRunning == true)
Log.i("Foreground App ", appProcess.processName);
else
Log.i("Not Working! ", appProcess.processName);
}
handler.postDelayed(runnable,200);
}
}
};
handler.postDelayed(runnable, 200);
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
}
Here is my Manifest file :
<?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="***************">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.REAL_GET_TASKS" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_TOP_ACTIVITY_INFO"/>
<uses-permission android:name="android.permission.INSTANT_APP_FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
<application
android:allowBackup="true"
android:icon="#mipmap/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.Dark">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".BackgroundService"
android:exported="true"
android:enabled="true"
/>
</application>
Never Ending Background Service is not possible but you can Limit Close Service
cause this will Take More Battery which Not Allowed
1- Use Forground Service
this will make service to be run with Notification Like Music App
2- Use START_STICKY
this will make your service start when it Killed
It was possible with a Broadcoast Receiver. But since Oreo (API 26) you can only perform that with a Job Scheduler.
In most cases, apps can work around these limitations by using
JobScheduler jobs. This approach lets an app arrange to perform work
when the app isn't actively running, but still gives the system the
leeway to schedule these jobs in a way that doesn't affect the user
experience. Android 8.0 offers several improvements to JobScheduler
that make it easier to replace services and broadcast receivers with
scheduled jobs.
See more at : https://developer.android.com/about/versions/oreo/background
I am working on Sony Remote camera which is connected using WiFi.I need to click a picture using a camera and then upload it to my FTP server which is in another activity.for than I need to disconnect my camera wifi and connect to the another wifi network or mobile data.when I connect to the another wifi/mobile data and going to upload the picture on FTP server I got this error.
IOException Unable to resolve host No address associated with hostname
When a close application and start again, And then directly upload pictures without connecting/disconnection camera than it works fine.
someone, please tell me how can I solve this, because I checked each and every solution on stack overflow and not one solution work for me.
I added bellow permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Connection to a network is not inmediate.
Also, if the desired network has no internet connection, in recent versions of Android it will not connect (if the connection is made by a user, a popup shows a confirmation to connnect).
I solved both problems using Android APIs (2 versions, one for API<21 and the other for API>=21).
Try this code (I'm using AndroidAnnotations for dependency injection, but is not required):
public class WifiHelper extends BroadcastReceiver {
#RootContext
Context context;
#SystemService
ConnectivityManager connectivityManager;
#SystemService
WifiManager wifiManager;
// For API>=21
private WifiHelperNetworkCallback wnc;
// For API<21
private boolean isBroadcastRegistered;
private String desiredSSID;
private Runnable callback;
public void enableNetwork(String ssid, int networkId, Runnable callback) {
desiredSSID = ssid;
wifiManager.enableNetwork(networkId, true);
configureNetworkRequest();
}
private void networkAvailable() {
// this method will be called when the network is available
callback.run();
}
private void configureNetworkRequest() {
if (android.os.Build.VERSION.SDK_INT >= 21) {
configureNetworkRequestAPI21();
} else {
configureNetworkRequestLegacy();
}
}
#TargetApi(21)
private void configureNetworkRequestAPI21() {
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
if (wnc == null) wnc = new WifiHelperNetworkCallback(this, connectivityManager);
connectivityManager.requestNetwork(request, wnc);
}
private void configureNetworkRequestLegacy() {
unregisterReceiver();
connectivityManager.startUsingNetworkFeature(ConnectivityManager.TYPE_WIFI, null);
IntentFilter intent = new IntentFilter();
intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intent.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
context.registerReceiver(this, intent);
isBroadcastRegistered = true;
}
#TargetApi(21)
private void disableNetworkRequest() {
if (android.os.Build.VERSION.SDK_INT >= 21) {
if (wnc != null) connectivityManager.unregisterNetworkCallback(wnc);
ConnectivityManager.setProcessDefaultNetwork(null);
} else {
unregisterReceiver();
}
}
private void unregisterReceiver() {
if (isBroadcastRegistered) {
context.unregisterReceiver(this);
isBroadcastRegistered = false;
}
}
// API<21
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
// Wifi is connected
if (desiredSSID.equals(getCurrentSSID())) {
// Callback and unregister
networkAvailable();
unregisterReceiver();
}
}
}
}
public String getCurrentSSID() {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null && wifiInfo.getSupplicantState()== SupplicantState.COMPLETED) {
return ssidWithoutQuotes(wifiInfo.getSSID());
}
else return null;
}
protected static String ssidWithoutQuotes(String ssid) {
if (ssid == null) return null;
else if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
return ssid.substring(1, ssid.length() - 1);
} else {
return ssid;
}
}
protected String getDesiredSSID() {
return desiredSSID;
}
#TargetApi(21)
public static class WifiHelperNetworkCallback extends ConnectivityManager.NetworkCallback {
public final String LOG_TAG = WifiHelper.class.getSimpleName();
private ConnectivityManager connectivityManager;
private WifiHelper wifiHelper;
public WifiHelperNetworkCallback(WifiHelper wifiHelper, ConnectivityManager connectivityManager) {
this.wifiHelper = wifiHelper;
this.connectivityManager = connectivityManager;
}
public void onAvailable(Network network) {
// Do something once the network is available
NetworkInfo info = connectivityManager.getNetworkInfo(network);;
Log.i(LOG_TAG, "networkcallback!! " + info.getExtraInfo());
String desiredSSID = wifiHelper.getDesiredSSID();
if (desiredSSID != null && desiredSSID.equals(ssidWithoutQuotes(info.getExtraInfo()))) {
ConnectivityManager.setProcessDefaultNetwork(network);
wifiHelper.networkAvailable();
}
}
}
}
You will need this permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" android:maxSdkVersion="18"/>
First i prompts the user to open the wifi or not.
I want to open the wifi if closed, scan all the wifi networks available and connect to certain one based on it's ssid.
I want to register a broad cast receiver to wait till the WifiManager to finish scanning results.
public class Project1 extends Activity {
/**
* Called when the activity is first created.
*/
EditText userName;
EditText passWord;
Button button;
TextView thankYou;
WifiManager wifiManager;
List<ScanResult> results1;
BroadcastReceiver receiver;
public Boolean connectToNetworK() {
Log.e("Start of connect","Debug");
Log.e("before wifi manager of connect","Debug");
if(!wifiManager.isWifiEnabled()){
Log.e("wifi is not enabled","Debug");
wifiManager.setWifiEnabled(true);
}
Log.e("after wifi manager of connect","Debug");
List<ScanResult>results =null;
Log.e("after scan result = null","Debug");
while(!wifiManager.isWifiEnabled())
{
Log.e("wifi still off","Debug");
}
Log.e("wifi is on","Debug");
Log.e("starting scan","Debug");
wifiManager.startScan();
Log.e("waiting","Debug");
if(results1!=null && !results1.isEmpty())
{
Log.e("Results1 is not emplty","Debug");
}
}
#Override
public void onStop()
{
unregisterReceiver(receiver);
}
public void onCreate(Bundle savedInstanceState) {
final Context contex = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(receiver == null){
Log.e("Registering reciver","mark");
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
Log.e("In broad cast reciver","mark");
results1 =wifiManager.getScanResults();
}
};
registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
}
if (!mWifi.isConnected()) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Open the Wifi");
alert.setMessage("Your Wifi is Currently Turned off, Would You like to turn it on?");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(connectToMobinilNetworK())
{
AfterWifiIsOn();
}
else{
Intent intent = new Intent(contex, ErrorPage.class);
startActivity(intent);}
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(contex, ErrorPage.class);
startActivity(intent);
}
});
alert.show();
} }
}
}
The list of scan resutls are always empty and the logs inside the broadcast receiver is not written.
Thanks in advance.
Do you have the correct permissions set up in your AndroidManifest? According to this guide, your permissions should look something like this:
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />