How to persist foreground service with geolocation service longer? - java

I have created a foreground service that gets user's geolocation after every 2 seconds the service than calculates the speed and performs some operation, the problem is application stops working after 24 hr and does not crash ( notification still in notification area remain ) and does not work in Oppo phones at all. Any help would be appreciated.
Thank you
Here is the code for my service
import android.app.KeyguardManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import org.json.JSONObject;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.File;
import java.io.FileWriter;
import java.util.Calendar;
import static java.lang.Math.acos;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
public class drivingService extends Service implements LocationListener {
// Declaration of Initialized Variables
public static int PRIMARY_FOREGROUND_NOTIF_SERVICE_ID = 1001, //Declaration of integers
progress = 0;
public static boolean enabled = true, //Declaration of boolean flags
popupEnabled = false,
sent = false,
first = true,
locked = false,
removed = false,
popup_visible = false,
tmp_visible = false;
// Declaration of Uninitialized Variables
public static NotificationCompat.Builder notification;
private static String TAG = "LOCATION_THINGS"; //Declaration of strings
private static String id = "";
public int drive = 0,
stop = 0;
public double lat1, lat2, lng1, lng2;
public long time1, time2;
NotificationManager mNotificationManager;
NotificationManagerCompat cNotificationManager;
Database db;
WindowManager windowManager;
WindowManager.LayoutParams params;
private LocationManager mLocationManager = null; //Declaration of location manager
private ImageView popup, stopping;
boolean networkStatus;
//Returns true and false idf the device is locked or not
public static boolean isDeviceLocked(Context context) {
boolean isLocked = false;
// First we check the locked state
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
boolean inKeyguardRestrictedInputMode = keyguardManager.inKeyguardRestrictedInputMode();
if (inKeyguardRestrictedInputMode) {
isLocked = true;
} else {
// If password is not set in the settings, the inKeyguardRestrictedInputMode() returns false,
// so we need to check if screen on for this case
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
isLocked = !powerManager.isInteractive();
} else {
//noinspection deprecation
isLocked = !powerManager.isScreenOn();
}
}
return isLocked;
}
//Create notification for service
public void createSimpleNotification() {
String GROUP_KEY_WORK_EMAIL = "com.blitzapp.textriteDriverAlert.not";
notification = new NotificationCompat.Builder(getApplicationContext(), id)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.large))
.setSmallIcon(R.drawable.not)
.setContentTitle("TextRite")
.setContentText("TextRite - Drive Mode is Enabled")
.setGroup(GROUP_KEY_WORK_EMAIL)
.setOngoing(false)
.setOnlyAlertOnce(true);
}
//Runs service powered by notification
public void renderNotification() {
cNotificationManager = NotificationManagerCompat.from(this);
cNotificationManager.notify(PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, notification.build());
startForeground(PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, notification.build());
}
//Creates Notification Channel
public void createNotificationChannel() {
id = "_channel_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(id, "TextRite - Drive Mode is Enabled", importance);
mChannel.enableLights(true);
mNotificationManager.createNotificationChannel(mChannel);
}
}
private void addToLogs(double speed, boolean alert, boolean tmp, boolean netwrok) {
try {
File root = new File(getFilesDir(), "speed_logs");
Log.d("Address", "" + getFilesDir());
if (!root.exists()) {
root.mkdir();
}
File filepath = new File(root, "logs.txt");
if (!filepath.exists()) {
filepath.createNewFile();
}
FileWriter writer = new FileWriter(filepath, true);
writer.append("Time->" + Calendar.getInstance().getTime() + "==|| Speed->" + speed + " || Alert Visible->" + alert + " || Temp Visible->" + tmp +"Network Status"+networkStatus+" || DB Count"+Database.dbCount+"\n");
writer.flush();
writer.close();
} catch (Exception ex) {
Log.e("File_I/O", "" + ex);
}
}
//Runs only once when the service is created
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
try {
createNotificationChannel();
createSimpleNotification();
renderNotification();
} catch (Exception ex) {
Toast.makeText(this, "" + ex, Toast.LENGTH_LONG).show();
}
}
//Event Emitter to stop service
private void sendEvent() {
MainApplication application = (MainApplication) this.getApplication();
ReactNativeHost reactNativeHost = application.getReactNativeHost();
ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
if (reactContext != null) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("stopService", null);
}
}
//This function is not used through out the code it is just added because of parent class service
#Override
public IBinder onBind(Intent arg0) {
return null;
}
//Adds alert to db when screen is locked
public void addAlert() {
try {
boolean networkStatus = isNetworkAvailable();
String alert = new Alert().getJsonObject();
db.insertAlert(alert);
if (networkStatus == true) {
db.sendData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Some Error Occurred while sending alerts to server.", Toast.LENGTH_LONG).show();
}
}
//Runs every time the service is started
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//Initialize database
db = new Database(getApplicationContext());
// Check If Force Stop button is presses
if (intent.getAction() != null && intent.getAction().equals("STOP")) {
stopForeground(true);
onDestroy();
} else {
// Check if switch is enabled then register location listener and create popup to render later
if (enabled) {
try {
getLocation();
createPopup();
//If any kind of mishap occurs report the user via toast message
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
// if switch not open by user then stop service
} else {
stopForeground(true);
onDestroy();
}
}
//If any kind of mishap occurs report the user via toast message
} catch (Exception ex) {
Toast.makeText(this, "Some Error Occurred while starting the service.", Toast.LENGTH_LONG).show();
}
return START_NOT_STICKY;
}
//Start the listener
private void getLocation() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
} catch (SecurityException ex) {
Toast.makeText(this, "Failed to request location update", Toast.LENGTH_LONG).show();
} catch (IllegalArgumentException ex) {
Toast.makeText(this, "GPS provider does not exist ", Toast.LENGTH_LONG).show();
}
}
//Take true or false in argument to render popup
public void clearAll() {
showTemp(false);
removed = true;
popupEnabled = false;
}
public void showPopup(boolean show) {
if (show == true) {
try {
stopping.setVisibility(View.INVISIBLE);
} catch (Exception e) {
}
popup.setVisibility(View.VISIBLE);
popup_visible = true;
popupEnabled = true;
} else {
popup.setVisibility(View.INVISIBLE);
popup_visible = false;
}
}
public void showTemp(boolean show) {
if (show == true) {
try {
popup.setVisibility(View.INVISIBLE);
} catch (Exception e) {
}
popupEnabled = true;
stopping.setVisibility(View.VISIBLE);
tmp_visible = true;
} else {
stopping.setVisibility(View.INVISIBLE);
tmp_visible = false;
}
}
//Creates popup or the alert window
private void createPopup() {
int LAYOUT_TYPE;
//Layout Parameters Declared
params = new WindowManager.LayoutParams();
//Setting Layout type According to build version of phone
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_TYPE = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_TYPE = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
}
//Setting Up Layout Type and other properties
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
params.type = LAYOUT_TYPE;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
params.format = PixelFormat.TRANSLUCENT;
params.gravity = Gravity.CENTER;
params.x = 0;
params.y = 0;
//Check if Service is enabled by user then create popup set its visibility to false for later use
try {
if (enabled) {
//Window Manager Initialized
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//Setting properties and parameters of popup to be viewed
popup = new ImageView(this);
popup.setImageResource(R.drawable.alert_potrait);
popup.setScaleType(ImageView.ScaleType.FIT_XY);
stopping = new ImageView(this);
stopping.setImageResource(R.drawable.stopping);
stopping.setScaleType(ImageView.ScaleType.FIT_XY);
windowManager.addView(popup, params);
windowManager.addView(stopping, params);
popup.setVisibility(View.INVISIBLE);
stopping.setVisibility(View.INVISIBLE);
}
//If any kind of mishap occurs report the user via toast message
} catch (Exception ex) {
Toast.makeText(this, "Some Error Occurred while creating Overlay Screen", Toast.LENGTH_LONG).show();
}
}
//Runs when is stopped
#Override
public void onDestroy() {
super.onDestroy();
try {
//set enabled service by user to false
enabled = false;
//disable popup visibility
popup.setVisibility(View.INVISIBLE);
//Unregister location manager for updates if it's not null
if (mLocationManager != null) {
mLocationManager.removeUpdates(this);
}
//send Event to React Native that service has stopped
sendEvent();
stopSelf();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Some Error Occurred, Restart your phone to avoid any inconvenience", Toast.LENGTH_LONG).show();
}
}
//Location Manager Initialization to access location listener
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
//Returns true and false is network is connected or not
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
//Runs Every 2 second and returns the current location of the device
#Override
public void onLocationChanged(Location location) {
// check if location is not null or value is not a garbage value
if (location != null) {
//setting up variables to calculate speed
lat2 = lat1;
lng2 = lng1;
time2 = time1;
lat1 = location.getLatitude();
lng1 = location.getLongitude();
time1 = location.getTime();
//calculations performed
double distance = getDistance(lat1, lng1, lat2, lng2);
double time = calcTime(time1, time2);
double speed = distance / time;
Log.d("error: ",location.toString());
try {
networkStatus = isNetworkAvailable();
if (networkStatus == true) {
JSONObject log;
log = new JSONObject();
log.put("type","location_inside_if");
log.put("location_object",location.toString());
log.put("latitude",location.getLatitude());
log.put("longitude",location.getLongitude());
log.put("get_speed",speed);
log.put("speed_calculated",location.getSpeed());
log.put("drive",drive);
log.put("stop",stop);
log.put("locked",locked);
Log.d("Location_object", log.toString());
db.sendLogsData(log);
db.sendData();
}
} catch (Exception e) {
}
//if speed is greater than 8
if (speed >= 8) {
drive++;
stop = 0;
if (locked == true) {
locked = false;
showPopup(true);
} else {
if (drive == 5) {
showPopup(true);
drive = 0;
}
}
}
// if speed in less than 8
else {
drive = 0;
stop++;
popup.setVisibility(View.INVISIBLE);
if (locked == true) {
//Log.d("Log_Lock", "JUST AFTER UNLOCK: locked = true");
locked = false;
if (stop >= 25 && tmp_visible == true) {
if (tmp_visible) {
//Log.d("Log_Lock", "JUST AFTER UNLOCK: temp time up / back to normal");
clearAll();
stop = 0;
}
} else if (stop == 0) {
if (popup_visible) {
showTemp(true);
Log.d("Log_Lock", "JUST AFTER UNLOCK: timer running");
}
}
} else {
//Log.d("Log_Lock", "JUST AFTER UNLOCK: locked = false " + popupEnabled + " " + popup_visible + " " + tmp_visible);
if (popup_visible) {
//Log.d("Log_Lock", "AFTER SOMETIME: show temp popup");
showPopup(false);
showTemp(true);
drive = 0;
} else if (tmp_visible) {
showTemp(true);
if (stop >= 25) {
//Log.d("Log_Lock", "AFTER SOMETIME: temp time up");
clearAll();
stop = 0;
}
}
else{
clearAll();
}
}
}
if (isDeviceLocked(getApplicationContext())) {
popup.setVisibility(View.INVISIBLE);
stopping.setVisibility(View.INVISIBLE);
locked = true;
if (sent == false) {
addAlert();
sent = true;
}
} else {
sent = false;
}
}else{
try {
networkStatus = isNetworkAvailable();
if (networkStatus == true) {
JSONObject log;
log = new JSONObject();
log.put("type","inside_location_null");
log.put("location_object",location.toString());
log.put("drive",drive);
log.put("stop",stop);
log.put("locked",locked);
db.sendLogsData(log);
db.sendData();
}
} catch (Exception e) {
}
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
try {
networkStatus = isNetworkAvailable();
if (networkStatus == true) {
JSONObject log;
log = new JSONObject();
log.put("type","onStatusChanged");
log.put("provider",provider);
log.put("status",status);
log.put("extras",extras);
log.put("drive",drive);
log.put("stop",stop);
log.put("locked",locked);
db.sendLogsData(log);
}
} catch (Exception e) {
}
}
#Override
public void onProviderEnabled(String provider) {
try {
networkStatus = isNetworkAvailable();
if (networkStatus == true) {
JSONObject log;
log = new JSONObject();
log.put("type","onProviderEnabled");
log.put("provider",provider);
log.put("drive",drive);
log.put("stop",stop);
log.put("locked",locked);
db.sendLogsData(log);
}
} catch (Exception e) {
}
}
#Override
public void onProviderDisabled(String provider) {
try {
networkStatus = isNetworkAvailable();
if (networkStatus == true) {
JSONObject log;
log = new JSONObject();
log.put("type","onProviderDisabled");
log.put("provider",provider);
log.put("drive",drive);
log.put("stop",stop);
log.put("locked",locked);
db.sendLogsData(log);
}
} catch (Exception e) {
}
}
//Returns the distance between two locations
double getDistance(double lat1, double lon1, double lat2, double lon2) {
double M_PI = Math.PI;
// Convert degrees to radians
lat1 = lat1 * M_PI / 180.0;
lon1 = lon1 * M_PI / 180.0;
lat2 = lat2 * M_PI / 180.0;
lon2 = lon2 * M_PI / 180.0;
// radius of earth in metres
double r = 6378100;
// P
double rho1 = r * cos(lat1);
double z1 = r * sin(lat1);
double x1 = rho1 * cos(lon1);
double y1 = rho1 * sin(lon1);
// Q
double rho2 = r * cos(lat2);
double z2 = r * sin(lat2);
double x2 = rho2 * cos(lon2);
double y2 = rho2 * sin(lon2);
// Dot product
double dot = (x1 * x2 + y1 * y2 + z1 * z2);
double cos_theta = dot / (r * r);
double theta = acos(cos_theta);
// Distance in Metres
Log.d("Dist DISTANCE", Double.toString(r * theta));
return r * theta;
}
//Returns time in milliseconds between two locations
private double calcTime(double t1, double t2) {
Log.d("DIS_DIFF", Double.toString((t1 - t2) / 1000));
return (t1 - t2) / 1000;
}
}

Related

E/AudioRecord: AudioFlinger could not create record track, status: -1

I had this error on my VoiSip Application
E/AudioRecord: AudioFlinger could not create record track, status: -1
E/AudioGroup: cannot initialize audio device
This error occurs after I'm trying to make call to another sip address
Here have 2 java class(WalkieTalkieActivity.java & IncomingCallReceiver.java)
WalkieTalkieActivity.java
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public IncomingCallReceiver callReceiver;
public SipManager mSipManager = null;
public SipProfile mSipProfile = null;
public SipAudioCall call = null;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walkie_talkie);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
if (mSipManager == null) {
mSipManager = SipManager.newInstance(this);
}
tv = (TextView)findViewById(R.id.textView);
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void closeLocalProfile() {
if (mSipManager == null) {
return;
}
try {
if (mSipProfile != null) {
mSipManager.close(mSipProfile.getUriString());
}
} catch (Exception ee) {
Log.d("onDestroy", "Failed to close local profile.", ee);
}
}
public void initializeManager() {
if(mSipManager == null) {
mSipManager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
private void initializeLocalProfile() {
String domain = "mydomain";
String username = "myusername";
String password = "mypassword";
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
mSipProfile = builder.build();
if (mSipProfile == null){
Log.e("error cukimai", "null");
}else{
Log.e("error cukimai", "not null");
}
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
mSipManager.open(mSipProfile, pi, null);
mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
Log.e("process","Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
Log.e("process","ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
Log.e("process","Registration failed. Please check settings.");
}
});
Log.e("process","stop");
} catch (SipException e) {
e.printStackTrace();
Log.e("error cukimai", "cuk cuk");
} catch (ParseException e) {
e.printStackTrace();
Log.e("error cukimai", "cuk");
}
}
public void updateStatus(final String st){
this.runOnUiThread(new Runnable() {
public void run() {
tv.setText(st);
}
});
}
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if(useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
public void callAct(View view) {
Toast.makeText(this, "about to make call", Toast.LENGTH_LONG).show();
makeCall();
}
public void makeCall(){
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = mSipManager.makeAudioCall(mSipProfile.getUriString(), "sip:destination#domain", listener, 30);
Log.e("make call", "true");
start();
}catch (Exception e){
Log.i("error", "Error when trying to close manager.", e);
if (mSipProfile != null) {
try {
mSipManager.close(mSipProfile.getUriString());
} catch (Exception ee) {
Log.i("error", "Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
#Override
public boolean onTouch(View view, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
final MediaRecorder recorder = new MediaRecorder();
final String path;
/**
* Creates a new audio recording at the given path (relative to root of SD card).
*/
public WalkieTalkieActivity(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}
/**
* Starts a new recording.
*/
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
/**
* Stops a recording that has been previously started.
*/
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
}
IncomingCallReceiver.java
public class IncomingCallReceiver extends BroadcastReceiver {
/**
* Processes the incoming call, answers it, and hands it over to the
* WalkieTalkieActivity.
* #param context The context under which the receiver is running.
* #param intent The intent being received.
*/
#Override
public void onReceive(Context context, Intent intent) {
SipAudioCall incomingCall = null;
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onRinging(SipAudioCall call, SipProfile caller) {
try {
call.answerCall(30);
} catch (Exception e) {
e.printStackTrace();
}
}
};
WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;
incomingCall = wtActivity.mSipManager.takeAudioCall(intent, listener);
incomingCall.answerCall(30);
incomingCall.startAudio();
incomingCall.setSpeakerMode(true);
if(incomingCall.isMuted()) {
incomingCall.toggleMute();
}
wtActivity.call = incomingCall;
wtActivity.updateStatus(incomingCall);
} catch (Exception e) {
if (incomingCall != null) {
incomingCall.close();
}
}
}
}
I'm really new on Sip and Voip Implementing in Android Studio. I got this code from google source code.
I believe this error occurs because of the use of hardware (audio). However I have been searching on google for almost 1 week and not giving results. Can someone help me?
I had same problem but when i changed targetSdkVersion to 12 in build.gradel its fixed.
and this answer helped me to fixed problem .
You must choose the BufferSize when you want to record or call in app. For example:
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize > 0 && bufferSize <= 256){
bufferSize = 256;
}else if (bufferSize > 256 && bufferSize <= 512){
bufferSize = 512;
}else if (bufferSize > 512 && bufferSize <= 1024){
bufferSize = 1024;
}else if (bufferSize > 1024 && bufferSize <= 2048){
bufferSize = 2048;
}else if (bufferSize > 2048 && bufferSize <= 4096){
bufferSize = 4096;
}else if (bufferSize > 4096 && bufferSize <= 8192){
bufferSize = 8192;
}else if (bufferSize > 8192 && bufferSize <= 16384){
bufferSize = 16384;
}else{
bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
}

Android app crash on Bluetooth LE write

I am developing an Android app to control stepper motors via a Android Due and a Bluetooth HM-10 BLE module.
So far everything works, but there seems to be a problem on some devices, which cause the app to crash. On my Nexus 5 and 7 it is working fine, but for example on a Samsung Galaxy S5 it keeps crashing. All devices have Andoird 6.0.1, so they should be equal.
I am getting this error report from the user:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothGattCharacteristic.setValue(byte[])' on a null object reference
at pm.puremoco.BluetoothLeService.WriteValue(BluetoothLeService.java:70)
at pm.puremoco.frag_moviesetlinear$3.onFinish(frag_moviesetlinear.java:266)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
So the error is occuring, when opening, at "onCreateView". There is the command to transmit a value:
mBluetoothLeService.WriteValue("1900_" + String.valueOf(variables.vidUpdateIntervall) + "#");
Here is almost the full fragment:
public class frag_moviesetlinear extends Fragment {
public static final String methodtocall = "ooo";
private final static String TAG = DeviceControlFragment.class.getSimpleName();
public AlertDialog alertTransmitData;
public BluetoothLeService mBluetoothLeService; //TODO evtl. private
public String methodcalled = "aaa";
public String dataLineReceived;
public long countDownTimerDelay = 200;
public AlertDialog alertTimeTooShort;
NumberPicker noPick1 = null;
NumberPicker noPick2 = null;
NumberPicker noPick3 = null;
long alertTransmitDataLength = 21000;
DeviceControlFragment devConFrag;
double minTimeFactor = 0;
TextView vid_maxSpeedU;
TextView vid_maxSpeedV;
TextView vid_maxSpeedW;
TextView vid_maxSpeedX;
TextView vid_maxSpeedY;
TextView vid_maxSpeedZ;
TextView vid_maxSpeedUspline;
TextView vid_maxSpeedVspline;
TextView vid_maxSpeedWspline;
TextView vid_maxSpeedXspline;
TextView vid_maxSpeedYspline;
TextView vid_maxSpeedZspline;
TextView txt_vidDuration;
TextView txt_vidUpdateIntervall;
TextView txt_minTime;
int timeForCalculation = 0;
int calculatedSpeedU = 0;
int calculatedSpeedV = 0;
int calculatedSpeedW = 0;
int calculatedSpeedX = 0;
int calculatedSpeedY = 0;
int calculatedSpeedZ = 0;
boolean movingHome = false;
private String mDeviceAddress;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
getActivity().finish();
}
Log.e(TAG, "mBluetoothLeService is okay");
// Log.e(TAG, mDeviceAddress);
// Automatically connects to the device upon successful start-up initialization.
if (mDeviceAddress == "---") {
Toast.makeText(getActivity(), "Bluetooth-Device not selected!", Toast.LENGTH_SHORT).show();
} else {
mBluetoothLeService.connect(mDeviceAddress);
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private String mDeviceName;
private TextView mDataField;
private Button btn_vidSplineStart;
private Button btn_vidUpdateIntervalNeg;
private Button btn_vidUpdateIntervalPos;
private boolean mConnected = false;
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { //���ӳɹ�
Log.e(TAG, "Only gatt, just wait");
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { //�Ͽ�����
mConnected = false;
getActivity().invalidateOptionsMenu();
// btnSend.setEnabled(false);
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) //���Կ�ʼ�ɻ���
{
mConnected = true;
// mDataField.setText("");
// ShowDialog();
//btnSend.setEnabled(true);
Log.e(TAG, "In what we need");
getActivity().invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { //�յ�����
Log.e(TAG, "RECV DATA");
final String data = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
Log.e(TAG, data);
if (data != null && data.substring(0, 1).equals("#") && data.substring(data.length() - 1).equals("$")) {
// if (mDataField.length() > 500)
// mDataField.setText("");
// mDataField.append(data);
dataLineReceived = data.substring(1, data.length() - 1);
ActionHandlerDataReceived();
}
}
}
};
private static IntentFilter makeGattUpdateIntentFilter() { //ע����յ��¼�
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothDevice.ACTION_UUID);
return intentFilter;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final Intent intent = getActivity().getIntent();
// mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
// mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mDeviceAddress = variables.BluetoothAddress;
mDeviceName = variables.BluetoothName;
methodcalled = intent.getStringExtra(methodtocall);
Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
Log.d(TAG, "Try to bindService=" + getActivity().bindService(gattServiceIntent, mServiceConnection, getActivity().BIND_AUTO_CREATE));
getActivity().registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void onPause() {
super.onPause();
try {
getActivity().unregisterReceiver(mGattUpdateReceiver);
}
catch(Exception e){
}
try {
getActivity().unbindService(mServiceConnection);
}
catch(Exception e){
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "We are in destroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.setmovie, null);
vid_maxSpeedU = (TextView) layout.findViewById(R.id.vid_maxSpeedU);
vid_maxSpeedU.setText(String.valueOf(variables.speedU));
vid_maxSpeedV = (TextView) layout.findViewById(R.id.vid_maxSpeedV);
vid_maxSpeedV.setText(String.valueOf(variables.speedV));
vid_maxSpeedW = (TextView) layout.findViewById(R.id.vid_maxSpeedW);
vid_maxSpeedW.setText(String.valueOf(variables.speedW));
vid_maxSpeedX = (TextView) layout.findViewById(R.id.vid_maxSpeedX);
vid_maxSpeedX.setText(String.valueOf(variables.speedX));
vid_maxSpeedY = (TextView) layout.findViewById(R.id.vid_maxSpeedY);
vid_maxSpeedY.setText(String.valueOf(variables.speedY));
vid_maxSpeedZ = (TextView) layout.findViewById(R.id.vid_maxSpeedZ);
vid_maxSpeedZ.setText(String.valueOf(variables.speedZ));
double duration = 3700 * (double) variables.vidUpdateIntervall / 1000;
txt_vidUpdateIntervall = (TextView) layout.findViewById(R.id.txt_vidUpdateIntervall);
txt_vidUpdateIntervall.setText(String.valueOf(variables.vidUpdateIntervall));
txt_vidDuration = (TextView) layout.findViewById(R.id.txt_vidDuration);
txt_vidDuration.setText(String.format("%.2f", duration) + " s");
vid_maxSpeedUspline = (TextView) layout.findViewById(R.id.vid_maxSpeedUspline);
vid_maxSpeedVspline = (TextView) layout.findViewById(R.id.vid_maxSpeedVspline);
vid_maxSpeedWspline = (TextView) layout.findViewById(R.id.vid_maxSpeedWspline);
vid_maxSpeedXspline = (TextView) layout.findViewById(R.id.vid_maxSpeedXspline);
vid_maxSpeedYspline = (TextView) layout.findViewById(R.id.vid_maxSpeedYspline);
vid_maxSpeedZspline = (TextView) layout.findViewById(R.id.vid_maxSpeedZspline);
txt_minTime = (TextView) layout.findViewById(R.id.txt_minTime);
btn_vidSplineStart = (Button) layout.findViewById(R.id.btn_vidSplineStart);
btn_vidSplineStart.setOnClickListener(new event_btn_vidSplineStart());
btn_vidUpdateIntervalPos = (Button) layout.findViewById(R.id.btn_vidUpdateIntervalPos);
btn_vidUpdateIntervalPos.setOnClickListener(new event_btn_vidUpdateIntervalPos());
btn_vidUpdateIntervalNeg = (Button) layout.findViewById(R.id.btn_vidUpdateIntervalNeg);
btn_vidUpdateIntervalNeg.setOnClickListener(new event_btn_vidUpdateIntervalNeg());
//-----start-button------
minTimeFactor = 0;
timeForCalculation = variables.vidUpdateIntervall;
new CountDownTimer(countDownTimerDelay * 1, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mBluetoothLeService.WriteValue("1900_" + String.valueOf(variables.vidUpdateIntervall) + "#");
}
}.start();
new CountDownTimer(countDownTimerDelay * 2, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mBluetoothLeService.WriteValue("2000_" + String.valueOf(variables.linearWithFade) + "#");
}
}.start();
//-----start-button------
transmitDataAlert("calculation");
return layout;
}
private void ActionHandlerDataReceived() {
String variable;
String value;
String[] parts = dataLineReceived.split("_"); // escape .
variable = parts[0];
value = parts[1];
switch (variable) {
case "vidMaxSpeedU":
vid_maxSpeedUspline.setText(String.valueOf(value));
variables.vid_maxSpeedUspline = Integer.parseInt(value);
calculatedSpeedU = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedU) {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorU = Double.valueOf(value) / variables.speedU;
if (minTimeFactor < FactorU) {
minTimeFactor = FactorU;
}
break;
case "vidMaxSpeedV":
vid_maxSpeedVspline.setText(String.valueOf(value));
variables.vid_maxSpeedVspline = Integer.parseInt(value);
calculatedSpeedV = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedV) {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorV = Double.valueOf(value) / variables.speedV;
if (minTimeFactor < FactorV) {
minTimeFactor = FactorV;
}
break;
case "vidMaxSpeedW":
vid_maxSpeedWspline.setText(String.valueOf(value));
variables.vid_maxSpeedWspline = Integer.parseInt(value);
calculatedSpeedW = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedW) {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorW = Double.valueOf(value) / variables.speedW;
if (minTimeFactor < FactorW) {
minTimeFactor = FactorW;
}
break;
case "vidMaxSpeedX":
vid_maxSpeedXspline.setText(String.valueOf(value));
variables.vid_maxSpeedXspline = Integer.parseInt(value);
calculatedSpeedX = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedX) {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorX = Double.valueOf(value) / variables.speedX;
if (minTimeFactor < FactorX) {
minTimeFactor = FactorX;
}
break;
case "vidMaxSpeedY":
vid_maxSpeedYspline.setText(String.valueOf(value));
variables.vid_maxSpeedYspline = Integer.parseInt(value);
calculatedSpeedY = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedY) {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorY = Double.valueOf(value) / variables.speedY;
if (minTimeFactor < FactorY) {
minTimeFactor = FactorY;
}
break;
case "vidMaxSpeedZ":
vid_maxSpeedZspline.setText(String.valueOf(value));
variables.vid_maxSpeedZspline = Integer.parseInt(value);
calculatedSpeedZ = Integer.parseInt(value);
if (Integer.parseInt(value) > variables.speedZ) {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FF14AA00"));
}
double FactorZ = Double.valueOf(value) / variables.speedZ;
if (minTimeFactor < FactorZ) {
minTimeFactor = FactorZ;
}
alertTransmitData.dismiss();
double vidMin = Math.ceil(minTimeFactor * timeForCalculation);
variables.vidMinIntervall = (int) vidMin;
//txt_minTime.setText(String.valueOf(variables.vidMinIntervall));
double duration = (3700 * (double) variables.vidMinIntervall) / 1000;
txt_minTime.setText(String.format("%.2f", duration) + " s");
if(variables.vidMinIntervall<=variables.vidUpdateIntervall) {
btn_vidSplineStart.setEnabled(true);
}
break;
case "movieFinished":
btn_vidSplineStart.setText("Move home");
btn_vidSplineStart.setEnabled(true);
movingHome = true;
alertTransmitData.dismiss();
break;
case "movieHome":
btn_vidSplineStart.setText("Start");
btn_vidSplineStart.setEnabled(true);
alertTransmitData.dismiss();
break;
}
}
void calculateNewSpeeds() {
//--------------U-Axis-----------------
if (variables.vid_maxSpeedUspline != 0) {
variables.vid_maxSpeedUspline = (timeForCalculation * calculatedSpeedU) / variables.vidUpdateIntervall;
vid_maxSpeedUspline.setText(String.valueOf(variables.vid_maxSpeedUspline));
if (variables.vid_maxSpeedUspline > variables.speedU) {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedUspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------V-Axis-----------------
if (variables.vid_maxSpeedVspline != 0) {
variables.vid_maxSpeedVspline = (timeForCalculation * calculatedSpeedV) / variables.vidUpdateIntervall;
vid_maxSpeedVspline.setText(String.valueOf(variables.vid_maxSpeedVspline));
if (variables.vid_maxSpeedVspline > variables.speedV) {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedVspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------W-Axis-----------------
if (variables.vid_maxSpeedWspline != 0) {
variables.vid_maxSpeedWspline = (timeForCalculation * calculatedSpeedW) / variables.vidUpdateIntervall;
vid_maxSpeedWspline.setText(String.valueOf(variables.vid_maxSpeedWspline));
if (variables.vid_maxSpeedWspline > variables.speedW) {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedWspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------X-Axis-----------------
if (variables.vid_maxSpeedXspline != 0) {
variables.vid_maxSpeedXspline = (timeForCalculation * calculatedSpeedX) / variables.vidUpdateIntervall;
vid_maxSpeedXspline.setText(String.valueOf(variables.vid_maxSpeedXspline));
if (variables.vid_maxSpeedXspline > variables.speedX) {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedXspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------Y-Axis-----------------
if (variables.vid_maxSpeedYspline != 0) {
variables.vid_maxSpeedYspline = (timeForCalculation * calculatedSpeedY) / variables.vidUpdateIntervall;
vid_maxSpeedYspline.setText(String.valueOf(variables.vid_maxSpeedYspline));
if (variables.vid_maxSpeedYspline > variables.speedY) {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedYspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
//--------------Z-Axis-----------------
if (variables.vid_maxSpeedZspline != 0) {
variables.vid_maxSpeedZspline = (timeForCalculation * calculatedSpeedZ) / variables.vidUpdateIntervall;
vid_maxSpeedZspline.setText(String.valueOf(variables.vid_maxSpeedZspline));
if (variables.vid_maxSpeedZspline > variables.speedZ) {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FFFF3434"));
} else {
vid_maxSpeedZspline.setTextColor(Color.parseColor("#FF14AA00"));
}
}
}
public void alert_TimeTooShort(int errorCase, int movieLengthSecondsNEW) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
// set title
alertDialogBuilder.setTitle("Error");
String errorMessage = "error";
// set dialog message
alertDialogBuilder
.setMessage(errorMessage)
.setCancelable(false);
alertDialogBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
});
// create alert dialog
alertTimeTooShort = alertDialogBuilder.create();
// show it
alertTimeTooShort.show();
}
public void transmitDataAlert(String type) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View promptView = layoutInflater.inflate(R.layout.alert_transmitdata, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(promptView);
final ProgressBar progressbar = (ProgressBar) promptView.findViewById(R.id.progressBar_transmitData);
final TextView txt_PleaseWait = (TextView) promptView.findViewById(R.id.txt_PleaseWait);
final TextView txt_timeRemainVideo = (TextView) promptView.findViewById(R.id.txt_timeRemainVideo);
final TextView txt_timeRemainVideoTXT = (TextView) promptView.findViewById(R.id.txt_timeRemainVideoTXT);
new CountDownTimer(alertTransmitDataLength, 1) {
public void onTick(long millisUntilFinished) {
int longtointRemain = (int) millisUntilFinished;
int longtointFull = (int) alertTransmitDataLength;
int percentprogress = 100 - ((100 * longtointRemain) / longtointFull);
progressbar.setProgress(percentprogress);
float duration = (float) millisUntilFinished/1000;
txt_timeRemainVideo.setText(String.format("%.1f", duration) + " s");
}
public void onFinish() {
}
}.start();
}
alertDialogBuilder.setCancelable(false);
alertTransmitData = alertDialogBuilder.create();
alertTransmitData.show();
}
class event_btn_vidSplineStart implements View.OnClickListener {
#Override
public void onClick(View v) {
btn_vidSplineStart.setEnabled(false);
btn_vidSplineStart.setText("Moving...");
new CountDownTimer(countDownTimerDelay * 1, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//MotionMode
mBluetoothLeService.WriteValue("1900_" + String.valueOf(variables.vidUpdateIntervall) + "#");
}
}.start();
new CountDownTimer(countDownTimerDelay * 2, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//MotionMode
mBluetoothLeService.WriteValue("1110_0#");
}
}.start();
alertTransmitDataLength = (long) variables.vidUpdateIntervall*3700;
if(movingHome==true){
transmitDataAlert("moveHome");
movingHome=false;
}
else {
transmitDataAlert("videomove");
}
}
}
class event_btn_vidUpdateIntervalPos implements View.OnClickListener {
#Override
public void onClick(View v) {
variables.vidUpdateIntervall++;
double duration = (3700 * (double) variables.vidUpdateIntervall) / 1000;
txt_vidDuration.setText(String.format("%.2f", duration) + " s");
txt_vidUpdateIntervall.setText(String.valueOf(variables.vidUpdateIntervall));
calculateNewSpeeds();
if(variables.vidMinIntervall<=variables.vidUpdateIntervall) {
btn_vidSplineStart.setEnabled(true);
}
else{
btn_vidSplineStart.setEnabled(false);
}
}
}
class event_btn_vidUpdateIntervalNeg implements View.OnClickListener {
#Override
public void onClick(View v) {
if (variables.vidUpdateIntervall > 1) {
variables.vidUpdateIntervall--;
}
double duration = (3700 * (double) variables.vidUpdateIntervall) / 1000;
txt_vidDuration.setText(String.format("%.2f", duration) + " s");
txt_vidUpdateIntervall.setText(String.valueOf(variables.vidUpdateIntervall));
calculateNewSpeeds();
if(variables.vidMinIntervall<=variables.vidUpdateIntervall) {
btn_vidSplineStart.setEnabled(true);
}
else{
btn_vidSplineStart.setEnabled(false);
}
}
}
}
And here is the full BluetoothLeService, which I got from the website of the HM-10 Bluetooth manufacturer:
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
import java.util.UUID;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothGatt mBluetoothGatt;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
public final static UUID UUID_NOTIFY =
UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
public final static UUID UUID_SERVICE =
UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
public BluetoothGattCharacteristic mNotifyCharacteristic;
public void WriteValue(String strValue)
{
mNotifyCharacteristic.setValue(strValue.getBytes());
mBluetoothGatt.writeCharacteristic(mNotifyCharacteristic);
}
public void findService(List<BluetoothGattService> gattServices)
{
Log.i(TAG, "Count is:" + gattServices.size());
for (BluetoothGattService gattService : gattServices)
{
Log.i(TAG, gattService.getUuid().toString());
Log.i(TAG, UUID_SERVICE.toString());
if(gattService.getUuid().toString().equalsIgnoreCase(UUID_SERVICE.toString()))
{
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
Log.i(TAG, "Count is:" + gattCharacteristics.size());
for (BluetoothGattCharacteristic gattCharacteristic :
gattCharacteristics)
{
if(gattCharacteristic.getUuid().toString().equalsIgnoreCase(UUID_NOTIFY.toString()))
{
Log.i(TAG, gattCharacteristic.getUuid().toString());
Log.i(TAG, UUID_NOTIFY.toString());
mNotifyCharacteristic = gattCharacteristic;
setCharacteristicNotification(gattCharacteristic, true);
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
return;
}
}
}
}
}
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
Log.i(TAG, "oldStatus=" + status + " NewStates=" + newState);
if(status == BluetoothGatt.GATT_SUCCESS)
{
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mBluetoothGatt.close();
mBluetoothGatt = null;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.w(TAG, "onServicesDiscovered received: " + status);
findService(gatt.getServices());
} else {
if(mBluetoothGatt.getDevice().getUuids() == null)
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
Log.e(TAG, "OnCharacteristicWrite");
}
#Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
int status)
{
Log.e(TAG, "OnCharacteristicWrite");
}
#Override
public void onDescriptorRead(BluetoothGatt gatt,
BluetoothGattDescriptor bd,
int status) {
Log.e(TAG, "onDescriptorRead");
}
#Override
public void onDescriptorWrite(BluetoothGatt gatt,
BluetoothGattDescriptor bd,
int status) {
Log.e(TAG, "onDescriptorWrite");
}
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int a, int b)
{
Log.e(TAG, "onReadRemoteRssi");
}
#Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int a)
{
Log.e(TAG, "onReliableWriteCompleted");
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
//final StringBuilder stringBuilder = new StringBuilder(data.length);
//for(byte byteChar : data)
// stringBuilder.append(String.format("%02X ", byteChar));
//intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
intent.putExtra(EXTRA_DATA, new String(data));
}
sendBroadcast(intent);
}
public class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* #return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* #param address The device address of the destination device.
*
* #return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
/*
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
*/
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
if(mBluetoothGatt != null)
{
mBluetoothGatt.close();
mBluetoothGatt = null;
}
mBluetoothGatt = device.connectGatt(this.getApplication(), false, mGattCallback);
//mBluetoothGatt.connect();
Log.d(TAG, "Trying to create a new connection.");
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
/*
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
*/
}
/**
* Request a read on a given {#code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {#code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* #param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
/**
* Enables or disables notification on a give characteristic.
*
* #param characteristic Characteristic to act on.
* #param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
/*
// This is specific to Heart Rate Measurement.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
*/
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {#code BluetoothGatt#discoverServices()} completes successfully.
*
* #return A {#code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) return null;
return mBluetoothGatt.getServices();
}
}

Latitude and longitude per pixel Google static maps

I have a static map, i know center coordinates in latitude and longitude, zoom level and image dimensions.
I don't understood if google static maps are already flattened and latitude and longitude per pixel are the same anywhere. If it's not like that i whant to know how can i calculate latidude and longitude per pixel and then meters per pixel , and how does that values vary with latitude .
P.S. I'm developing an android application that download an static map and computes distance between 2 points , but i've done that asuming the lat and long per pixel are the same ...and doesn't depend on latitude(position on globe)
Here is my mainactivity
package com.mnav.nav;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.*;
import java.net.*;
import org.apache.http.*;
import android.graphics.*;
import java.io.*;
import android.graphics.drawable.*;
public class MainActivity extends Activity
{ Button start, dist;
TextView txt;
EditText lat, longit, zoom;
ImageView img;
Handler mhandler ;
Bitmap bit, original;
Boolean run = false, firstpoint = false, secondpoint = false;
String z, latitude, longitude;
int level;
int[] pointa = new int[2];
int[] pointb = new int[2];
double unit;
int maxx, maxy, minx, miny, distx, disty, distance1;
double distance;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(Button)findViewById(R.id.button);
lat = (EditText)findViewById(R.id.latitude);
longit = (EditText)findViewById(R.id.longitude);
img = (ImageView)findViewById(R.id.img);
zoom =(EditText)findViewById(R.id.zoom);
dist = (Button)findViewById(R.id.dist);
txt = (TextView)findViewById(R.id.txt);
mhandler = new Handler();
start.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{ z = zoom.getText().toString();
latitude = lat.getText().toString();
longitude = longit.getText().toString();
Thread thr = new Thread(new GetImage());
thr.start();
}
});
img.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{ int i, j;
int x = (int)event.getX();
int vertical = (int)event.getY();
if(secondpoint==true)
{ bit = original.copy(Bitmap.Config.ARGB_4444, true);
img.setImageBitmap(bit);
secondpoint = false;
}
txt.setText(Integer.toString(x)+ " "+Integer.toString(vertical));
for (i = x-2; i < x+3; i++)
{
for(j=vertical-2; j<vertical+3; j++)
{
bit.setPixel(i,j, Color.WHITE);
}
}
bit.setPixel(x,vertical,Color.GREEN);
img.setImageBitmap(bit);
if(firstpoint)
{
pointb[0] = x; pointb[1]=vertical;
secondpoint = true;
firstpoint = false;
}
else
{
pointa[0]=x; pointa[1]=vertical;
firstpoint=true;
}
return false;
}
});
dist.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View p1)
{
unit = 0.1412/800;
unit = unit*500;
level = Integer.parseInt(z);
if(level == 20)
{
unit = unit;
}
else
if(level == 19)
{
unit = unit*2;
}
else
if(level==18)
{
unit = unit*4;
}
else
if(level == 17)
{
unit =unit*8;
}
else
if(level==16)
{
unit = unit*16;
}
else
if(level==15)
{
unit = unit*32;
}
else
if(level==14)
{
unit = unit*64;
}
else
if(level==13)
{
unit = unit*128;
}
else
if(level == 12)
{
unit = unit*256;
}
else
if(level==11)
{
unit = unit*512;
}
else
if(level==10)
{
unit = unit*1024;
}
distx = Math.abs(pointa[0]-pointb[0]);
disty= Math.abs(pointa[1]-pointb[1]);
distance1 = distx*distx+disty*disty;
distance = Math.sqrt(distance1);
distance = unit*distance;
txt.setText(Double.toString(distance)+" meters");
}
});
}
public class GetImage implements Runnable
{
String Url = "http://maps.google.com/staticmap?center=" + latitude+","+longitude+"&format=png&zoom="+ z +"&size=500x500&scale=1&maptype=hybrid&key=ABQIAAAA-O3c-Om9OcvXMOJXreXHAxRexG7zW5nSjltmIc1ZE-b8yotBWhQYQEU3J87QIBc4nfuySpoW_K6woA";
Bitmap bmp;
#Override
public void run()
{
try
{ mhandler.post(new Runnable()
{
#Override
public void run()
{
txt.setText("Wait...file is downloading...");
}
});
bmp = BitmapFactory.decodeStream((InputStream)new URL(Url).getContent());
}
catch (IOException e)
{ mhandler.post(new Runnable()
{
#Override
public void run()
{
// TODO: Implement this method
Toast.makeText(getApplicationContext(), "Something wrong just happend", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
mhandler.post(new Runnable()
{
#Override
public void run()
{
if (bmp!=null)
{ txt.setText("Map downloaded..");
img.setImageBitmap(bmp);
bit = ((BitmapDrawable)img.getDrawable()).getBitmap();
bit = bit.copy(Bitmap.Config.ARGB_4444, true);
original = bit.copy(Bitmap.Config.ARGB_4444, true);
}
else
{
mhandler.post(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "null bitmap, sorry", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
}
}

Android: Record video and play mp3 simultaneously?

Is there a way to play a mp3 (or other) audio file while the camera is recording a video (without sound) on Android 4.x?
Has anybody ever tried to achieve this?
I've tried to play sound while recording sound and it was working, so I'm quite sure it is possible when recording video as well. You just need to have separate threads for video recording and sound playing.
package com.technologies.mash.MySounds.Music;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.technologies.mash.CameraPreview;
import com.technologies.mash.PlayVideo;
import com.technologies.mash.R;
import com.technologies.mash.Sound;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class AlbumDetailVideo extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private MediaRecorder mediaRecorder;
private Button capture, switchCamera;
private Context myContext;
private RelativeLayout cameraPreview;
AudioManager audioManager;
private boolean cameraFront = false;
// private ArrayList<Sound> mSounds = null;
int z = 0;
Sound s1;
MediaPlayer mPlayer;
int sound;
String urls;
String audio, root, video, video_new, output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_album_detail_video);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getting songpath from server
Intent i = getIntent();
urls = i.getStringExtra("songpath");
// String urls = getIntent().getExtras().getString("songpath");
Toast.makeText(AlbumDetailVideo.this, "Sound id" + urls, Toast.LENGTH_SHORT).show();
Log.e("url", urls);
// mSounds = new ArrayList<Sound>();
myContext = this;
initialize();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private String readTxt() {
InputStream inputStream = getResources().openRawResource(z);//getting the .txt file
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
private int findBackFacingCamera() {
int cameraId = -1;
// Search for the back facing camera
// get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
// for every camera check
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
// if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findBackFacingCamera());
mCamera.setDisplayOrientation(90);
mPreview.refreshCamera(mCamera);
}
}
public void initialize() {
cameraPreview = (RelativeLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (Button) findViewById(R.id.button_capture);
capture.setOnClickListener(captrureListener);
switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
switchCamera.setOnClickListener(switchCameraListener);
}
View.OnClickListener switchCameraListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the number of cameras
if (!recording) {
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
// release the old camera instance
// switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
}
};
public void chooseCamera() {
// if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
// open the backFacingCamera
// set a picture callback
// refresh the preview
mCamera = Camera.open(cameraId);
mCamera.setDisplayOrientation(90);
// mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
// open the backFacingCamera
// set a picture callback
// refresh the preview
mCamera = Camera.open(cameraId);
mCamera.setDisplayOrientation(90);
// mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
// when on Pause, release camera in order to be used from other
// applications
releaseCamera();
}
private boolean hasCamera(Context context) {
// check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
boolean recording = false;
View.OnClickListener captrureListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(AlbumDetailVideo.this, "Playing.." + urls, Toast.LENGTH_SHORT).show();
if (recording) {
// stop recording and release camera
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mPlayer.stop();
Intent intent = new Intent(getApplicationContext(), PlayVideo.class);
startActivity(intent);
finish();
Toast.makeText(AlbumDetailVideo.this, "Video captured!", Toast.LENGTH_LONG).show();
recording = false;
} else {
if (!prepareMediaRecorder()) {
Toast.makeText(AlbumDetailVideo.this, "Fail in prepareMediaRecorder()!\n - Ended -", Toast.LENGTH_LONG).show();
finish();
}
// work on UiThread for better performance
runOnUiThread(new Runnable() {
public void run() {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(urls);
} catch (IllegalArgumentException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(AlbumDetailVideo.this, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mediaRecorder.start();
mPlayer.start();
}
});
recording = true;
}
}
};
private void releaseMediaRecorder() {
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
// CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
// mediaRecorder.setAudioSource(MediaRecorder.AudioEncoder.AAC_ELD);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
/* mediaRecorder.setOutputFormat(profile.fileFormat);
mediaRecorder.setVideoEncoder(profile.videoCodec);
mediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
mediaRecorder.setVideoFrameRate(profile.videoFrameRate);
mediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);*/
mediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
try {
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
} catch (Exception e) {
}
mediaRecorder.setOutputFile("/sdcard/rohit.mp4");
mediaRecorder.setMaxDuration(600000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
/* private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
//mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
try {
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
}catch (Exception e){
}
mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
mediaRecorder.setMaxDuration(600000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}*/
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}

How to decode JSON data sent to server by TripTracker?

I am using a PHP MySQL server model. I want to decode the JSON data that is sent to the server by this code. Any help would be appreciated. The app sends current GPS coordinates to inputed server as JSON array object. I would like to decode it to share with other android users. Thanks a lot. This is the Android code.
public class TrackerService extends Service {
private static final String TAG = "TripTracker/Service";
private final String updatesCache = "updates.cache";
public static TrackerService service;
private NotificationManager nm;
private Notification notification;
private static boolean isRunning = false;
private String freqString;
private int freqSeconds;
private String endpoint;
private final int MAX_RING_SIZE = 15;
private LocationListener locationListener;
private AlarmManager alarmManager;
private PendingIntent pendingAlarm;
private static volatile PowerManager.WakeLock wakeLock;
private AsyncTask httpPoster;
ArrayList<LogMessage> mLogRing = new ArrayList<LogMessage>();
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
ArrayList<List> mUpdates = new ArrayList<List>();
final ReentrantReadWriteLock updateLock = new ReentrantReadWriteLock();
final Messenger mMessenger = new Messenger(new IncomingHandler());
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_LOG = 3;
static final int MSG_LOG_RING = 4;
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
#Override
public void onCreate() {
super.onCreate();
TrackerService.service = this;
endpoint = Prefs.getEndpoint(this);
freqSeconds = 0;
freqString = null;
freqString = Prefs.getUpdateFreq(this);
if (freqString != null && !freqString.equals("")) {
try {
Pattern p = Pattern.compile("(\\d+)(m|h|s)");
Matcher m = p.matcher(freqString);
m.find();
freqSeconds = Integer.parseInt(m.group(1));
if (m.group(2).equals("h"))
freqSeconds *= (60 * 60);
else if (m.group(2).equals("m"))
freqSeconds *= 60;
}
catch (Exception e) {
}
}
if (endpoint == null || endpoint.equals("")) {
logText("invalid endpoint, stopping service");
stopSelf();
}
if (freqSeconds < 1) {
logText("invalid frequency (" + freqSeconds + "), stopping " +
"service");
stopSelf();
}
readCache();
showNotification();
isRunning = true;
/* we're not registered yet, so this will just log to our ring buffer,
* but as soon as the client connects we send the log buffer anyway */
logText("service started, requesting location update every " +
freqString);
/* findAndSendLocation() will callback to this */
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
sendLocation(location);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
/* we don't need to be exact in our frequency, try to conserve at least
* a little battery */
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, AlarmBroadcast.class);
pendingAlarm = PendingIntent.getBroadcast(this, 0, i, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), freqSeconds * 1000, pendingAlarm);
}
#Override
public void onDestroy() {
super.onDestroy();
if (httpPoster != null)
httpPoster.cancel(true);
try {
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
}
catch (Exception e) {
}
/* kill persistent notification */
nm.cancelAll();
if (pendingAlarm != null)
alarmManager.cancel(pendingAlarm);
isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
/* must be done inside of updateLock */
public void cacheUpdates() {
OutputStreamWriter cacheStream = null;
try {
FileOutputStream cacheFile = TrackerService.this.openFileOutput(
updatesCache, Activity.MODE_PRIVATE);
cacheStream = new OutputStreamWriter(cacheFile, "UTF-8");
/* would be nice to just serialize mUpdates but it's not
* serializable. create a json array of json objects, each object
* having each key/value pair of one location update. */
JSONArray ja = new JSONArray();
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
JSONObject jo = new JSONObject();
for (int j = 0; j < pair.size(); j++) {
try {
jo.put(((NameValuePair)pair.get(j)).getName(),
pair.get(j).getValue());
}
catch (JSONException e) {
}
}
ja.put(jo);
}
cacheStream.write(ja.toString());
cacheFile.getFD().sync();
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
}
/* read json cache into mUpdates */
public void readCache() {
updateLock.writeLock().lock();
InputStreamReader cacheStream = null;
try {
FileInputStream cacheFile = TrackerService.this.openFileInput(
updatesCache);
StringBuffer buf = new StringBuffer("");
byte[] bbuf = new byte[1024];
int len;
while ((len = cacheFile.read(bbuf)) != -1)
buf.append(new String(bbuf));
JSONArray ja = new JSONArray(new String(buf));
mUpdates = new ArrayList<List>();
for (int j = 0; j < ja.length(); j++) {
JSONObject jo = ja.getJSONObject(j);
List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
Iterator<String> i = jo.keys();
while (i.hasNext()) {
String k = (String)i.next();
String v = jo.getString(k);
nvp.add(new BasicNameValuePair(k, v));
}
mUpdates.add(nvp);
}
if (mUpdates.size() > 0)
logText("read " + mUpdates.size() + " update" +
(mUpdates.size() == 1 ? "" : "s") + " from cache");
}
catch (JSONException e) {
}
catch (FileNotFoundException e) {
}
catch (IOException e) {
Log.w(TAG, e);
}
finally {
if (cacheStream != null) {
try {
cacheStream.close();
}
catch (IOException e) {
}
}
}
updateLock.writeLock().unlock();
}
/* called within wake lock from broadcast receiver, but assert that we have
* it so we can keep it longer when we return (since the location request
* uses a callback) and then free it when we're done running through the
* queue */
public void findAndSendLocation() {
if (wakeLock == null) {
PowerManager pm = (PowerManager)this.getSystemService(
Context.POWER_SERVICE);
/* we don't need the screen on */
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"triptracker");
wakeLock.setReferenceCounted(true);
}
if (!wakeLock.isHeld())
wakeLock.acquire();
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
locationListener, null);
}
public static boolean isRunning() {
return isRunning;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.icon,
"Trip Tracker Started", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker",
"Sending location every " + freqString, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT;
nm.notify(1, notification);
}
private void updateNotification(String text) {
if (nm != null) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Trip Tracker", text,
contentIntent);
notification.when = System.currentTimeMillis();
nm.notify(1, notification);
}
}
public void logText(String log) {
LogMessage lm = new LogMessage(new Date(), log);
mLogRing.add(lm);
if (mLogRing.size() > MAX_RING_SIZE)
mLogRing.remove(0);
updateNotification(log);
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
Bundle b = new Bundle();
b.putString("log", log);
Message msg = Message.obtain(null, MSG_LOG);
msg.setData(b);
mClients.get(i).send(msg);
}
catch (RemoteException e) {
/* client is dead, how did this happen */
mClients.remove(i);
}
}
}
/* flatten an array of NameValuePairs into an array of
* locations[0]latitude, locations[1]latitude, etc. */
public List<NameValuePair> getUpdatesAsArray() {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i < mUpdates.size(); i++) {
List<NameValuePair> pair = mUpdates.get(i);
for (int j = 0; j < pair.size(); j++)
pairs.add(new BasicNameValuePair("locations[" + i + "][" +
((NameValuePair)pair.get(j)).getName() + "]",
pair.get(j).getValue()));
}
return pairs;
}
public int getUpdatesSize() {
return mUpdates.size();
}
public void removeUpdate(int i) {
mUpdates.remove(i);
}
private void sendLocation(Location location) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
pairs.add(new BasicNameValuePair("time",
String.valueOf(location.getTime())));
pairs.add(new BasicNameValuePair("latitude",
String.valueOf(location.getLatitude())));
pairs.add(new BasicNameValuePair("longitude",
String.valueOf(location.getLongitude())));
pairs.add(new BasicNameValuePair("speed",
String.valueOf(location.getSpeed())));
/* push these pairs onto the queue, and only run the poster if another
* one isn't running already (if it is, it will keep running through
* the queue until it's empty) */
updateLock.writeLock().lock();
mUpdates.add(pairs);
int size = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
logText("location " +
(new DecimalFormat("#.######").format(location.getLatitude())) +
", " +
(new DecimalFormat("#.######").format(location.getLongitude())) +
(size <= 1 ? "" : " (" + size + " queued)"));
if (httpPoster == null ||
httpPoster.getStatus() == AsyncTask.Status.FINISHED)
(httpPoster = new HttpPoster()).execute();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
/* respond with our log ring to show what we've been up to */
try {
Message replyMsg = Message.obtain(null, MSG_LOG_RING);
replyMsg.obj = mLogRing;
msg.replyTo.send(replyMsg);
}
catch (RemoteException e) {
}
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
default:
super.handleMessage(msg);
}
}
}
/* Void as first arg causes a crash, no idea why
E/AndroidRuntime(17157): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[]
*/
class HttpPoster extends AsyncTask<Object, Void, Boolean> {
#Override
protected Boolean doInBackground(Object... o) {
TrackerService service = TrackerService.service;
int retried = 0;
int max_retries = 4;
while (true) {
if (isCancelled())
return false;
boolean failed = false;
updateLock.writeLock().lock();
List<NameValuePair> pairs = service.getUpdatesAsArray();
int pairSize = service.getUpdatesSize();
updateLock.writeLock().unlock();
AndroidHttpClient httpClient =
AndroidHttpClient.newInstance("TripTracker");
try {
HttpPost post = new HttpPost(endpoint);
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse resp = httpClient.execute(post);
int httpStatus = resp.getStatusLine().getStatusCode();
if (httpStatus == 200) {
/* all good, we can remove everything we've sent from
* the queue (but not just clear it, in case another
* one jumped onto the end while we were here) */
updateLock.writeLock().lock();
for (int i = pairSize - 1; i >= 0; i--)
service.removeUpdate(i);
updateLock.writeLock().unlock();
}
else {
logText("POST failed to " + endpoint + ": got " +
httpStatus + " status");
failed = true;
}
}
catch (Exception e) {
logText("POST failed to " + endpoint + ": " + e);
Log.w(TAG, e);
failed = true;
}
finally {
if (httpClient != null)
httpClient.close();
}
if (failed) {
/* if our initial request failed, snooze for a bit and try
* again, the server might not be reachable */
SystemClock.sleep(15 * 1000);
if (++retried > max_retries) {
/* give up since we're holding the wake lock open for
* too long. we'll get it next time, champ. */
logText("too many failures, retrying later (queue " +
"size " + service.getUpdatesSize() + ")");
break;
}
}
else
retried = 0;
int q = 0;
updateLock.writeLock().lock();
q = service.getUpdatesSize();
cacheUpdates();
updateLock.writeLock().unlock();
if (q == 0)
break;
/* otherwise, run through the rest of the queue */
}
return false;
}
protected void onPostExecute(Boolean b) {
if (wakeLock != null && wakeLock.isHeld())
wakeLock.release();
}
}
}
You can decode the data using json_decode()
<?php
$json = ""; // JSON data
$json_obj = json_decode($json); // As Object
$json_arr = json_decide($json,true) // As Array
var_dump($json_obj);
print_r($json_arr);
// Store Array to database using serialize function
$data = serialize($json_array); // Array will be converted into string
?>

Categories

Resources