How to make Call recorder in android studio - java

I made a call recorder that works sometimes but sometimes it doesn't work, I searched about it but I can't solve this problem, here is my code:
public class RecordingService extends Service {
private MediaRecorder rec;
private boolean recorderstarted;
private File file;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);
Date date = new Date();
CharSequence sdf = DateFormat.format("MM-dd-yy-hh-mm-ss", date.getTime());
rec = new MediaRecorder();
String manufacturer = Build.MANUFACTURER;
rec.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
rec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
rec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
rec.setOutputFile(file.getAbsolutePath() + "/" + sdf + "rec.3gp");
MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
public void onError(MediaRecorder arg0, int arg1, int arg2) {
Toast.makeText(getApplicationContext(), "Crashed", Toast.LENGTH_SHORT).show();
}
};
rec.setOnErrorListener(errorListener);
TelephonyManager manager = (TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);
manager.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String phoneNumber) {
// super.onCallStateChanged(state, phoneNumber){
if (TelephonyManager.CALL_STATE_IDLE == state
&& recorderstarted
) {
Log.i("Hello", "onCallStateChanged: Before stoptel" + (TelephonyManager.CALL_STATE_IDLE == state) );
Log.i("Hello", "onCallStateChanged: Before stoprec" + (recorderstarted) );
rec.stop();
rec.reset();
rec.release();
recorderstarted = false;
stopSelf();
Log.i("Hello", "onCallStateChanged: After stoptel" + (TelephonyManager.CALL_STATE_IDLE == state) );
Log.i("Hello", "onCallStateChanged: After stoprec" + (recorderstarted) );
} else if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
try {
Log.i("Hello", "onCallStateChanged: Before start" + (TelephonyManager.CALL_STATE_OFFHOOK == state));
rec.prepare();
// Thread.sleep(2000);
rec.start();
recorderstarted = true;
Log.i("Hello", "onCallStateChanged: After start" + (TelephonyManager.CALL_STATE_OFFHOOK == state));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
return START_STICKY;
// return super.onStartCommand(intent, flags, startId);
}
}
I made this app from this video, Thanks for taking time to answer my question, if you need code from other class please comment under my question,
I added the runtime permission code and I added the permission code to my manifest but my problem was not solved, please help me, Thanks (-:

You should change AudioSource VOICE_COMMUNICATION to VOICE_CALL
rec.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
To
rec.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL)
And add permission
<uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" tools:ignore="ProtectedPermissions" />
into Manifest file. But your app should be as a system app. You can root your phone to make your app as system app or directly add your app to AOSP.

Related

Android onLocationChanged does not called

I am trying to implement a background GPS location service in android using Service and LocationListener. The service is started (-> the onCreate and onStartCommand methods are called), but the onLocationChanged method never called.
Here is the code of my Service:
public class GpsHandler extends Service implements LocationListener{
private static final String TAG = "GpsHandler";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private final String LOCATION_BROADCAST_TAG = "android.LOCATION";
private final String LOCATION_EXTRA_TAG = "Location";
private Location mLastLocation = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Toast.makeText(this, "Service Started, onCreate", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started, onStartCommand", Toast.LENGTH_LONG).show();
if (mLocationManager == null)
{
mLocationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
mLastLocation = new Location(LocationManager.GPS_PROVIDER);
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, this);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mLocationManager != null)
{
try {
mLocationManager.removeUpdates(this);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "Gps is turned off!! ",
Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location)
{
Toast.makeText(this, "Location Changed", Toast.LENGTH_LONG).show();
if(isBetterLocation(location,mLastLocation))
{
mLastLocation.set(location);
Intent intent = new Intent(LOCATION_BROADCAST_TAG).putExtra(LOCATION_EXTRA_TAG, location);
sendBroadcast(intent);
}
}
#Override
public void onProviderEnabled(String provider){}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){}
private boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > 1000*30;//30000ms = 30 sec
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer)
{
return true;
// If the new location is more than two minutes older, it must be worse
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
}
Finally I have found the solution. I have tried to debug it with an other emulator (Originally I have used Pixel C emulator) and now it works flawless. So it is just a Studio Bug, the code is working.I have also restructured the code a bit, removing some useless functions:
Working code:
public class GpsHandler extends Service implements LocationListener{
private static final String TAG = "GpsHandler";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0f;
private final String LOCATION_BROADCAST_TAG = "android.LOCATION";
private final String LOCATION_EXTRA_TAG = "Location";
private Location mLastLocation = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Toast.makeText(this, "Service Started, onCreate", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started, onStartCommand", Toast.LENGTH_LONG).show();
if (mLocationManager == null)
{
mLocationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
mLastLocation = new Location(LocationManager.GPS_PROVIDER);
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, this);
mLastLocation.set(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mLocationManager != null)
{
try {
mLocationManager.removeUpdates(this);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "Gps is turned off!! ",
Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location)
{
Toast.makeText(this, "Location Changed", Toast.LENGTH_LONG).show();
if(location.getAccuracy()<4*mLastLocation.getAccuracy())
{
mLastLocation.set(location);
Intent intent = new Intent(LOCATION_BROADCAST_TAG).putExtra(LOCATION_EXTRA_TAG, location);
sendBroadcast(intent);
}
}
#Override
public void onProviderEnabled(String provider){}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){}
}

Android - Service takes a long time to restart when forcibly killed

When I kill all the apps (including my app) running using a task killer, the service shows Restarting for a long time.
How do I improve on this ?
The best case scenario would be like, as soon as the app/service is killed, the service would spring up immediately or within the slightest delay possible.
WLANSrvice.java
public class WLANService extends Service {
String username, password, ssid, url;
private static final String CREDENTIALS = "Credentials";
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = getSharedPreferences(CREDENTIALS, 0);
if(sharedPreferences.contains("username")) {
username = sharedPreferences.getString("username", "UNDEFINED");
}
if(sharedPreferences.contains("password")) {
password = sharedPreferences.getString("password", "UNDEFINED");
}
if(sharedPreferences.contains("ssid")) {
ssid = sharedPreferences.getString("ssid", "UNDEFINED");
}
if(sharedPreferences.contains("url")) {
url = sharedPreferences.getString("url", "UNDEFINED");
}
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean connected = info.isConnected();
if(connected) {
Toast.makeText(context, "WIFI CONNECTED!", Toast.LENGTH_LONG).show();
Log.i("Wi-Fi-State", "Wi-Fi is On!");
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if(wifiInfo.getSSID().contains(ssid) == true) {
try {
String output = new Connection().execute().get().toString();
Log.i("LoginState", new Connection().execute().get().toString());
if(output.contains("Address")) {
Toast.makeText(WLANService.this, "Login Success!", Toast.LENGTH_SHORT).show();
Intent account_info_intent = new Intent(WLANService.this, AccountInfo.class);
account_info_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(account_info_intent);
}else {
if(output.contains("n/a")) {
Toast.makeText(WLANService.this, "Login Failed!", Toast.LENGTH_SHORT).show();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(context, "WIFI DISCONNECTED!", Toast.LENGTH_SHORT).show();
//Log.i("Wi-Fi-State", "Wi-Fi is Off!");
}
}
};
public WLANService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Auto-Login Enabled!", Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// registering your receiver
registerReceiver(receiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Auto-Login Disabled!", Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
super.onDestroy();
}
private class Connection extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
String formatted_url = url.replace("http://", "");
String true_url;
if(formatted_url.charAt((formatted_url.length()-1)) != '/') {
true_url = formatted_url.concat("/");
}else {
true_url = formatted_url;
}
Log.i("formatted_url", formatted_url);
Log.i("true_url", true_url);
return LoginHelper.doLogin(username, password, "http://".concat(true_url));
}
}
}

Android: Firebase Update Issue When the app is in background

Hey I m going to develop an location tracker app in which, this app in client device which constantly send it location to the firebase db.
Here the problem is that it will send the data to firebase only first 3 minutes then it wont. I don't know whats happening. ?
For that even i put a log message that log message is printed perfectly even after three minutes
Any one please help on this........!
Here i attached 3 file One BackgroundLocation: Which is the service in background which will extract the device location and call the LocationReceiver which extends broadcast receiver where it will print log message and send the data to firebase through FBSender.
Thanks in advance
BackgroundLocation.java
Which runs in Background to get the location details and call the broadcast Reveiver. LocationReveiver.java
/**
* Created by geekyint on 1/7/16.
*/
public class BackgroundLocation extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
IBinder mBinder = new LocalBinder();
private GoogleApiClient mGoogleApiClient;
private PowerManager.WakeLock mWakeLock;
private LocationRequest mlocationRequest;
//Flag for boolean request
private boolean mInProgress;
private boolean serviceAvailabe = false;
public class LocalBinder extends Binder {
public BackgroundLocation getServerInstance() {
return BackgroundLocation.this;
}
}
#Override
public void onCreate() {
super.onCreate();
mInProgress = false;
//Create the lcoation request object
mlocationRequest = LocationRequest.create();
//Use the acurecy
mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//The INTERVAL
mlocationRequest.setInterval(Constants.UPDATE_INTERVAL);
//The FAST INTERVAL
mlocationRequest.setFastestInterval(Constants.FAST_INTERVAL);
serviceAvailabe = serviceConnected();
setUpALocationClientIfNeeded();
ComponentName receiver = new ComponentName(this, LocationReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
/*ComponentName receiver1 = new ComponentName(this, FireBaseSender.class);
PackageManager pm1 = this.getPackageManager();
pm1.setComponentEnabledSetting(receiver1,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
}
private void setUpALocationClientIfNeeded() {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
}
//Create the new Connection to the client
private void buildGoogleApiClient() {
this.mGoogleApiClient = new GoogleApiClient.Builder(this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
private boolean serviceConnected() {
//Check the google Play service availibility
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
//IF AVAILABLE
if (resultCode == ConnectionResult.SUCCESS) {
return true;
} else {
return false;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (this.mWakeLock == null) {
this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
}
if (!this.mWakeLock.isHeld()) {
this.mWakeLock.acquire();
}
if (!serviceAvailabe || mGoogleApiClient.isConnected() || mInProgress) {
return START_STICKY;
}
setUpALocationClientIfNeeded();
if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() || !mInProgress) {
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
mInProgress = true;
mGoogleApiClient.connect();
}
return START_STICKY;
}
#Override
public void onLocationChanged(Location location) {
String msg = Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Log.d("debug", msg);
// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ":" + msg, Constants.LOCATION_FILE);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDestroy() {
// Turn off the request flag
this.mInProgress = false;
if (this.serviceAvailabe && this.mGoogleApiClient != null) {
this.mGoogleApiClient.unregisterConnectionCallbacks(this);
this.mGoogleApiClient.unregisterConnectionFailedListener(this);
this.mGoogleApiClient.disconnect();
// Destroy the current location client
this.mGoogleApiClient = null;
}
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ":
// Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
if (this.mWakeLock != null) {
this.mWakeLock.release();
this.mWakeLock = null;
}
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Stopped", Constants.LOG_FILE);
ComponentName receiver = new ComponentName(this, LocationReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
/*
ComponentName receiver1 = new ComponentName(this, FireBaseSender.class);
PackageManager pm1 = this.getPackageManager();
pm1.setComponentEnabledSetting(receiver1,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);*/
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
// Request location updates using static settings
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Intent intent = new Intent (this, LocationReceiver.class);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
mlocationRequest, pendingIntent);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onConnectionSuspended(int i) {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mGoogleApiClient = null;
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected", Constants.LOG_FILE);
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
// If no resolution is available, display an error dialog
} else {
}
}
}
Here The LocationReceiver Code:
public class LocationReceiver extends BroadcastReceiver {
private String TAG = this.getClass().getSimpleName();
private LocationResult mLocationResult;
private double latitude;
private double longitude;
private double speed;
private String time;
#Override
public void onReceive(Context context, Intent intent) {
// Need to check and grab the Intent's extras like so
if(LocationResult.hasResult(intent)) {
this.mLocationResult = LocationResult.extractResult(intent);
//new SaveToFireB().insertToFireBase(mLocationResult.getLastLocation());
new FBSender().put(mLocationResult.getLastLocation());
Log.i(TAG, "Location Received: " + this.mLocationResult.toString());
String msg = String.valueOf(mLocationResult.getLastLocation().getLongitude()) + " " +
String.valueOf(mLocationResult.getLastLocation().getLatitude());
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ":" + msg, Constants.LOCATION_FILE);
}
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here Which will call FBSender to send the data to firebase.
Ther real problems comes here.
It will send the data only in first three minutes then it wont send the data to firebase
For confirmation whether the control going there or not i put log message there that log message will be printed perfectly even after 3 minutes from the start of the app
Here is FBSender.Java
public class FBSender extends Service {
private String TAG = "FBSender";
private double latitude;
private double longitude;
private double speed;
private String time;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void put (Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
speed = location.getSpeed();
time = DateFormat.getTimeInstance().format(new Date());
Log.e(TAG, "Entering the run ()");
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference reference = database.getReference("users/" + user.getUid() + "/vehicles");
Log.e(TAG, "I M in the middle");
Map mLocations = new HashMap();
mLocations.put("latitude", latitude);
mLocations.put("longitude", longitude);
mLocations.put("speed", speed);
mLocations.put("time", time);
reference.setValue(mLocations);
Log.e(TAG, "Exiting The run ()");
}
}
To get more information about why the database writes are not completing after 3 minutes, add a CompetionListener to your setValue():
reference.setValue(mLocations, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Log.i(TAG, "onComplete: OKAY");
} else {
Log.e(TAG, "onComplete: FAILED " + databaseError.getMessage());
}
}
});
When you hit the 3 minute mark, if the callback fires with an error, such as permission failure, you can investigate why. If it stops firing at all, that probably means you've lost connection with the Firebase server. You can monitor the connection status using a listener, as described in the documentation.

How to keep android camera flash on after screen locked

I'm creating a flash light app for android. I'm using service to turn on and off flash. All things are works fine. But when screen locked flash light is automatically turning off and service already running. this happen only device unplugged from charger. when device charging flash light keep turn on after screen locked.How can I avoid this problem.
Here is my FlashLightService.java file
public class FlashLightService extends Service {
Camera camera;
Camera.Parameters parameters;
static boolean isTurnOn;
static int usedTime = 0;
static String TAG = "coretorch_service";
Thread t;
static String formattedTime;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Torch turned on", Toast.LENGTH_SHORT).show();
isTurnOn = true;
t =new Thread(new Runnable() {
#Override
public void run() {
while (isTurnOn){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
usedTime++;
}
usedTime = 0;
}
});
t.start();
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
camera.release();
isTurnOn = false;
super.onDestroy();
Toast.makeText(this, "Torch turned off", Toast.LENGTH_SHORT).show();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public static boolean getFlashStatus() {
return isTurnOn;
}
public static String getUsedTime(){
formattedTime = toTimeFormat(usedTime);
return formattedTime;
}
static String toTimeFormat(int secs){
String time;
int mins;
int seconds;
if (secs < 60){
time = String.valueOf(secs) + " sec";
}
else {
mins = (secs / 60);
seconds = (secs - (mins * 60));
time = String.valueOf(mins) + " mins " + String.valueOf(seconds) + " sec";
}
return time;
}
}
#Override
protected void onPause() {
Camera.open().getParameters().setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
};
Can you do something like this? I have never played with camera

How do I put a capped maximum directory storage space in SD?

Presumingly i wanted to allocate only 1GB of space to store my videos in a particular file directory where how is it going to auto-delete the oldest video file in that directory once its about to reach/hit 1GB?
Sorry i'm kinna new in java/android and currently creating an car blackbox app can someone help me... Thanks
This is what I have tried so far can someone tell me how should i implement the above mention function into my CameraTest Activity:
public class CameraTest extends Activity implements SurfaceHolder.Callback, OnClickListener {
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera MainCamera;
private static boolean previewRunning;
private static boolean serviceRunning = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceView.setOnClickListener(this);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnSetting = (Button) findViewById(R.id.button2);
btnSetting.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startActivity(new Intent(getApplicationContext(), SettingActivity.class));
}
});
}
#Override
public void onClick(View v) {
if (serviceRunning)
{
serviceRunning = false;
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
else
{
serviceRunning = true;
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
}
public static boolean ServiceStatus;
public static String resParams;
#Override
public void surfaceCreated(SurfaceHolder holder) {
if(ServiceRecording.recordingStatus)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
try {
Thread.sleep(4000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
MainCamera = ServiceRecording.ServiceCamera;
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
else{
MainCamera = Camera.open();
if (MainCamera != null) {
resParams = MainCamera.getParameters().get("preview-size-values");
Camera.Parameters params = MainCamera.getParameters();
params.setPreviewSize(320, 240);
params.setPreviewFormat(PixelFormat.JPEG);
MainCamera.setParameters(params);
try {
MainCamera.setPreviewDisplay(holder);
}
catch (IOException e)
{
e.printStackTrace();
}
MainCamera.startPreview();
previewRunning = true;
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
if (previewRunning) {
MainCamera.stopPreview();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
MainCamera.stopPreview();
previewRunning = false;
MainCamera.release();
}
}
my serviceRecording.java file
public class ServiceRecording extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;
#Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
{
//new Timer().scheduleAtFixedRate(task, after, interval);
startRecording();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
private MediaRecorder mediaRecorder;
private static int encodingType;
private static String videoResolution;
private static String fileFormat;
private static boolean audioStatus;
private static int timeInterval;
private static final String TAG = "Exception";
public boolean startRecording(){
try {
if(Tab1Activity.encodingPref == null)
{
encodingType = 1;
}
else
{
encodingType = Integer.parseInt(Tab1Activity.encodingPref);
}
//******************************************************************
if(Tab1Activity.videoResPref == null)
{
String stringRes = CameraTest.resParams;
String[] entriesValues = stringRes.split(",");
videoResolution = entriesValues[0];
}
else
{
videoResolution = Tab1Activity.videoResPref;
}
//******************************************************************
if(Tab1Activity.fileFormatPref == null)
{
fileFormat = ".mp4";
}
else
{
fileFormat = Tab1Activity.fileFormatPref;
}
//******************************************************************
if(Tab2Activity.audioPref == false)
{
audioStatus = false;
//PreferenceManager.setDefaultValues(this, R.xml.tab2, true);
}
else
{
audioStatus = Tab2Activity.audioPref;
}
//******************************************************************
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.reconnect();
ServiceCamera.unlock();
}
catch(Exception e){
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
if(audioStatus != true)
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
if(audioStatus != true)
{
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
}
mediaRecorder.setVideoEncoder(encodingType);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
String[] separatedRes = videoResolution.split("x");
mediaRecorder.setVideoSize(Integer.parseInt(separatedRes[0]),Integer.parseInt(separatedRes[1]));
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.reset();
mediaRecorder.release();
recordingStatus = false;
}
}
To get the current size of a directory, you need add up the sizes of each individual file in a directory using the length() method. This article is what you're looking for in that respect. You can then check if the size has exceeded 1 GB.
In terms of auto-deleting the oldest file you can do the following:
File directory = new File(*String for absolute path to directory*);
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
file[0].delete();
This code gets all your files in an array, and sorts them depending on their modified/created date. Then the first file in your array is your oldest file, therefore you can just simply delete it.
The best place to put this in your code is when you're about to write something to a directory. Perform this check and deletion first, and then if the size is less than 1 GB, write to directory, otherwise delete another file.

Categories