can anyone help me why not the accelerometer nőt stops?
There's the unregisterListener line but nothing.
Here is the code:
public class Festivale extends Activity implements SensorEventListener {
Button button;
CheckBox video, gps, acc;
Boolean recording = false;
public static SQLiteDatabase db;
String strlocation;
String city;
private SensorManager sensorManager;
Chronometer myChronometer;
EditText myEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myChronometer = (Chronometer) findViewById(R.id.chronometer);
myEditText = (EditText) findViewById(R.id.editText1);
addDataBase(); // adatbázist hoz létre
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Készítette: Lakatos Dávid\nEmail: david.lakatos#gmail.com\nTel.: +3620/427-1166")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
private void addGPSListener() {
String text = myEditText.getText().toString();
float f = Float.valueOf(text.trim()).floatValue();
float update = f * 1000;
if (update < 100 || update > 1000000) {
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(Festivale.this).create();
alertDialog.setTitle("Hiba!");
alertDialog.setMessage("Helytelen frissítési idõ:\n" + update
/ 1000 + " sec!");
alertDialog.show();
} else {
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocListener = new MyLocationListener();
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 0,
globalconstant.mlocListener);
}
}
/* Létrehozzuk a program adatbázisát */
private void addDataBase() throws SQLException {
db = openOrCreateDatabase("Festivale.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
}
public void addListenerOnButton() {
button = (Button) findViewById(R.id.button1);
button.setEnabled(true);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
gps = (CheckBox) findViewById(R.id.checkBox1);
acc = (CheckBox) findViewById(R.id.checkBox2);
video = (CheckBox) findViewById(R.id.checkBox3);
/*
* GPS
*/
if (gps.isChecked()) {
if (recording) {
globalconstant.mlocManager
.removeUpdates(globalconstant.mlocListener);
button.setText("Start");
recording = false;
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
acc.setClickable(true);
video.setClickable(true);
myEditText.setFocusable(true);
gps.setChecked(false);
} else {
acc.setClickable(false);
video.setClickable(false);
myEditText.setFocusable(false);
myChronometer.setBase(SystemClock.elapsedRealtime());
myChronometer.start();
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String gps =
"CREATE TABLE IF NOT EXISTS GPS_Values ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 8), Longitude float(10, 8),Horizontal_Accuracy INTEGER,Altitude INTEGER,City TEXT,cur_timestamp TIMESTAMP);";
db.execSQL(gps);
addGPSListener();// meghívja a gps-t
recording = true;
button.setText("STOP");
}
}
/*
* Gyorsulásmérõ
*/
if (acc.isChecked()) {
if (recording) {
StopListenerAcc();
button.setText("Start");
recording = false;
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
gps.setClickable(true);
video.setClickable(true);
myEditText.setFocusable(true);
acc.setChecked(false);
} else {
gps.setClickable(false);
video.setClickable(false);
myEditText.setFocusable(false);
myChronometer.setBase(SystemClock.elapsedRealtime());
myChronometer.start();
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String acc =
"CREATE TABLE IF NOT EXISTS Accelerometer ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, X_Coordinate float(10, 6), Y_Coordinate float(10, 6), Z_Coordinate float(10, 6), cur_timestamp TIMESTAMP);";
db.execSQL(acc);
// Bekapcsolja az Accelerometer-t
addListenerAcc();
recording = true;
button.setText("STOP");
}
}
/*
* VideoRögzítés meghívása
*/
if (video.isChecked()) {
// kamera meghívása
Intent myIntent = new Intent(Festivale.this, record.class);
Festivale.this.startActivity(myIntent);
}
}
});
}
private void StopListenerAcc() {
// TODO Auto-generated method stub
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// add listener
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.unregisterListener(this);
}
// GPS
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
float szel = (float) loc.getLatitude();
float hossz = (float) loc.getLongitude();
int horiAcc = (int) (loc.getAccuracy());
int Altitude = (int) (loc.getAltitude());
String test = String.format("%.08f", szel);
String test2 = String.format("%.08f", hossz);
Geocoder geocoder = new Geocoder(Festivale.this,
Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(szel, hossz,
1);
city = addresses.get(0).getLocality();
// Toast.makeText(getApplicationContext(), city,
// Toast.LENGTH_SHORT)
// .show();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues gps_values = new ContentValues();
gps_values.put("Latitude", test);
gps_values.put("Longitude", test2);
gps_values.put("Horizontal_Accuracy", horiAcc);
gps_values.put("Altitude", Altitude);
gps_values.put("City", city);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
gps_values.put("cur_timestamp", dateFormat.format(date));
try {
db.beginTransaction();
db.insert("GPS_Values", null, gps_values);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
// String Text = "My current location is: " + "Latitude = "
// + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();
// Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT)
// .show();
}
protected void onPause() {
// super.onPause();
globalconstant.mlocManager
.removeUpdates(globalconstant.mlocListener);
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// show gps otions
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.cancel();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(
Festivale.this);
builder.setMessage("A GPS nincs aktiválva!\nAktiválja most?")
.setPositiveButton("Aktivál", dialogClickListener)
.setNegativeButton("Nem", dialogClickListener).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}// gps vége
private void addListenerAcc() {
// TODO Auto-generated method stub
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// add listener
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
// Accelerometer
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// assign directions
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
// Toast.makeText(Festivale.this,
// "X: " + x + "\nY: " + y + "\nZ: " + z, Toast.LENGTH_LONG)
// .show();
ContentValues x_values = new ContentValues();
x_values.put("X_Coordinate", x);
x_values.put("Y_Coordinate", y);
x_values.put("Z_Coordinate", z);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
x_values.put("cur_timestamp", dateFormat.format(date));
db.insert("Accelerometer", null, x_values);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
thx!
How about trying this to unregister you accelerometer (works for me):
/**
* <b><i>public void useAccelerometer(boolean use)</i></b>
* <br>
* Since: API 1
* <br>
* <br>
* Set if you would like to enable the use of the accelerometer.
*
* #param use
* <br>
* True will enable the use of the accelerometer.
* <br>
* False will disable the use of the accelerometer.
*
*/
public void useAccelerometer(boolean use) {
if(use == true) {
manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
}
else {
manager.unregisterListener(this, accelerometer);
}
}
Related
I am developing recording application. In that it will record all incoming and outgoing calls and am displayed these calls in ListView. I want to display separate symbols for incoming and outgoing recording files. How can I separate it? Please provide solution. If possible provide source code.
Thank you.
CallBroadCastReceiver.java
public class CallBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("CallRecorder", "CallBroadcastReceiver:onReceive got Intent: " + intent.toString());
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String numberToCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.d("CallRecorder", "CallBroadcastReceiver intent has EXTRA_PHONE_NUMBER: " + numberToCall);
}
PhoneListener phoneListener = new PhoneListener(context);
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Log.d("PhoneStateReceiver:onReceive", "set PhoneStateListener");
}
}
PhoneListener.java
public class PhoneListener extends PhoneStateListener {
private Context context;
public PhoneListener(Context c) {
Log.i("CallRecorder", "PhoneListener constructor");
context = c;
}
public void onCallStateChanged(int state, String incomingNumber) {
Log.d("CallRecorder", "PhoneListener::onCallStateChanged state:" + state + " incomingNumber:" + incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("CallRecorder", "CALL_STATE_IDLE, stoping recording");
Boolean stopped = context.stopService(new Intent(context, RecordService.class));
Log.i("CallRecorder", "stopService for RecordService returned " + stopped);
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d("CallRecorder", "CALL_STATE_RINGING");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("CallRecorder", "CALL_STATE_OFFHOOK starting recording");
Intent callIntent = new Intent(context, RecordService.class);
ComponentName name = context.startService(callIntent);
if (null == name) {
Log.e("CallRecorder", "startService for RecordService returned null ComponentName");
} else {
Log.i("CallRecorder", "startService returned " + name.flattenToString());
}
break;
}
}
}
CallLog.java
public class CallLoglist extends Activity {
private final String TAG = "CallRecorder";
private ListView fileList = null;
//public static ArrayAdapter<String> fAdapter = null;
private SeekBar seekbar;
private MediaPlayer mediaPlayer = new MediaPlayer();
public static ImageButton pauseButton;
public TextView startTimeField, endTimeField;
AudioManager audioManager;
public static final String STORAGE_LOCATIONN = Environment.getExternalStorageDirectory() + "/Android/data/com.callrecorder/favourites";
Handler seekHandler = new Handler();
Dialog seekDialog;
private Utilities utils;
long totalDuration, currentDuration;
public static ImageView img;
String[] dlist;
String recordlist;
private list fAdapter;
ArrayList<String> alist;
Cursor managedCursor;
StringBuffer sb;
public String name;
public String number;
File source;
CallLoglist cc;
public static boolean ss;
String phNumber;
public static int a;
public static Editor ed;
public static SharedPreferences pref;
public static ArrayList<Boolean> arr = new ArrayList<Boolean>();
private class CallItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.showContextMenu();
CharSequence s = (CharSequence) parent.getItemAtPosition(position);
Log.w(TAG, "CallLog just got an item clicked: " + s);
//File f = new File(RecordService.DEFAULT_STORAGE_LOCATION + "/" + s.toString());
/*boolean useMediaController = true;
if (useMediaController) {
Intent playIntent = new Intent(getApplicationContext(), CallPlayer.class); //Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(f);
playIntent.setData(uri);
startActivity(playIntent);
} else {
playFile(s.toString());
}*/
}
}
#SuppressLint("ShowToast")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
setContentView(R.layout.call_log);
fileList = (ListView) findViewById(R.id.play_file_list);
img = (ImageView) findViewById(R.id.image);
Context context = getApplicationContext();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
utils = new Utilities();
File dir = new File(RecordService.LOCATION);
dlist = dir.list();
alist = new ArrayList<String>(Arrays.asList(dlist));
Log.v("fille", "recording file" + recordlist);
fAdapter = new list(this, alist);
fileList.setAdapter(fAdapter);
fileList.setOnItemClickListener(new CallItemClickListener());
registerForContextMenu(fileList);
pref = getSharedPreferences("mm", MODE_PRIVATE);
ed = pref.edit();
/* ed.putString("rr", "R.drawable.arrow");
ed.putString("re", "R.drawable.arroww");*/
ed.commit();
////////////////
/*String[] projection = new String[] {android.provider.CallLog.Calls.NUMBER, android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.CACHED_NAME};
Uri contacts = android.provider.CallLog.Calls.CONTENT_URI;
Cursor managedCursor = managedQuery(contacts, projection, null, null, android.provider.CallLog.Calls.DATE + " ASC");
getColumnData(managedCursor);
}
private void getColumnData(Cursor cur){
try{
if (cur.moveToFirst()) {
long date;
int nameColumn = cur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int numberColumn = cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = cur.getColumnIndex(android.provider.CallLog.Calls.DATE);
System.out.println("Reading Call Details: ");
do {
name = cur.getString(nameColumn);
number = cur.getString(numberColumn);
date = cur.getLong(dateColumn);
System.out.println(number + ":"+ new Date(date) +":"+name);
} while (cur.moveToNext());
}
}
finally{
cur.close();
}*/
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater m = getMenuInflater();
m.inflate(R.menu.nn, menu);
}
#SuppressLint({"ShowToast", "SdCardPath"})
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
recordlist = alist.get(index);
//pp=dlist.
switch (item.getItemId()) {
case R.id.play:
seekDialog = new Dialog(this);
seekDialog.setTitle("play");
seekDialog.setContentView(R.layout.dialog);
startTimeField = (TextView) seekDialog.findViewById(R.id.textView1);
endTimeField = (TextView) seekDialog.findViewById(R.id.textView2);
pauseButton = (ImageButton) seekDialog.findViewById(R.id.imageButton2);
seekbar = (SeekBar) seekDialog.findViewById(R.id.seek);
seekDialog.show();
Log.v("file", "" + index);
if (mediaPlayer != null) {
mediaPlayer.release();
}
/*mediaPlayer=MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/com.callrecorder/recordings/" +pathh ));*/
mediaPlayer = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/com.callrecorder/recordings/" + recordlist));
mediaPlayer.start();
seekUpdation();
totalDuration = mediaPlayer.getDuration();
seekbar.setMax((int) totalDuration);
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
pauseButton.setImageResource(R.drawable.play);
Toast.makeText(getApplicationContext(), "pause", 1000).show();
} else {
mediaPlayer.start();
pauseButton.setImageResource(R.drawable.pause);
Toast.makeText(getApplicationContext(), "play", 1000).show();
}
}
});
seekDialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
mediaPlayer.release();
}
});
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mediaPlayer.pause();
seekbar.setProgress(mediaPlayer.getCurrentPosition());
seekbar.setMax(mediaPlayer.getDuration());
mediaPlayer.seekTo(progress);
mediaPlayer.start();
pauseButton.setImageResource(R.drawable.pause);
seekUpdation();
}
}
});
break;
case R.id.delete:
Toast.makeText(getApplicationContext(), "delete", 1000).show();
//new File(Environment.getExternalStorageDirectory()+"/callrecorder/" + pathh).delete();
new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.callrecorder/recordings/" + recordlist).delete();
alist.remove(index);
alist.clear();
fAdapter.notifyDataSetChanged();
fAdapter.notifyDataSetInvalidated();
break;
case R.id.favorites:
Toast.makeText(getApplicationContext(), "favouraties", 1000).show();
source = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.callrecorder/recordings/" + recordlist);
File dir = new File(STORAGE_LOCATIONN);
if (!dir.exists()) {
try {
dir.mkdir();
} catch (Exception e) {
// TODO: handle exception
}
}
try {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(STORAGE_LOCATIONN + "/" + recordlist);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
// TODO: handle exception
Log.v("copyyy", "errorrrrr");
}
source.delete();
alist.remove(index);
fAdapter.notifyDataSetChanged();
fAdapter.notifyDataSetInvalidated();
break;
default:
}
return super.onContextItemSelected(item);
}
Runnable runn = new Runnable() {
#Override
public void run() {
try {
seekUpdation();
} catch (Exception e) {
// TODO: handle exception
}
try {
totalDuration = mediaPlayer.getDuration();
currentDuration = mediaPlayer.getCurrentPosition();
// Displaying Total Duration time
endTimeField.setText("" + utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
startTimeField.setText("" + utils.milliSecondsToTimer(currentDuration));
seekbar.setProgress((int) currentDuration); //move seek bar
// Updating progress bar
/* int progress = (int)(utils.getProgressPercentage(currentDuration,totalDuration));
//Log.d("Progress", ""+progress);
seekbar.setProgress(progress);*/
// seekHandler.postDelayed(this, 100);
} catch (Exception e) {
// TODO: handle exception
}
}
};
public void seekUpdation() {
//seekbar.setProgress(mediaPlayer.getCurrentPosition());
//mHandler.postDelayed(mUpdateTimeTask, 100);
seekHandler.postDelayed(runn, 1000);
}
public void onStart() {
super.onStart();
Log.i(TAG, "CallLog onStart");
}
public void onRestart() {
super.onRestart();
Log.i(TAG, "CallLog onRestart");
}
/*public void onResume()
{
super.onResume();
//Log.i(TAG, "CallLog onResume about to load recording list again, does this work?");
loadRecordingsFromDir();
}*/
#Override
protected void onDestroy() {
/*if(null!=mediaPlayer){
mediaPlayer.release();
}*/
super.onDestroy();
if (mediaPlayer != null) {
//mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
///////////////////////////////////////////
private class list extends BaseAdapter {
private CallLoglist callLog;
private ArrayList<String> alist;
public list(CallLoglist callLog, ArrayList<String> alist) {
// TODO Auto-generated constructor stub
this.callLog = callLog;
this.alist = alist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return alist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.calllist, parent, false);
TextView textView = (TextView) v.findViewById(R.id.text);
ImageView imageView = (ImageView) v.findViewById(R.id.image);
textView.setText(alist.get(position));
String aa = pref.getString("rr", "");
String dd = pref.getString("re", "");
if (aa.equals("0")) {
imageView.setImageResource(R.drawable.arrow);
} else {
imageView.setImageResource(R.drawable.arroww);
}
//imageView.setImageResource(R.drawable.arrow);
//TextView text=(TextView)v.findViewById(R.id.namee);
/*if(arr.get(position))
{
imageView.setImageResource(R.drawable.arrow);
}
else {
imageView.setImageResource(R.drawable.arroww);
}*/
return v;
}
}
}
Recordservice.java
public class RecordService
extends Service
implements MediaRecorder.OnInfoListener, MediaRecorder.OnErrorListener {
private static final String TAG = "CallRecorder";
//public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/callrecorder";
public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/Android/data/com.callrecorder/recordings";
private static final int RECORDING_NOTIFICATION_ID = 1;
private MediaRecorder recorder = null;
private boolean isRecording = false;
private String incoming;
private Toast size;
public static File recording = null;
;
Intent intent;
private File makeOutputFile(SharedPreferences prefs) {
File dir = new File(DEFAULT_STORAGE_LOCATION);
// test dir for existence and writeability
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
Log.e("CallRecorder", "RecordService:makeOutputFile unable to create directory " + dir + ": " + e);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create the directory " + dir + " to store recordings: " + e, Toast.LENGTH_LONG);
t.show();
return null;
}
} else {
if (!dir.canWrite()) {
Log.e(TAG, "RecordService:makeOutputFile does not have write permission for directory: " + dir);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder does not have write permission for the directory directory " + dir + " to store recordings", Toast.LENGTH_LONG);
t.show();
return null;
}
}
String prefix = "cal";
//String prefix= PhoneListener.incoming;
int audiosource = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1"));
//prefix += "-" + audiosource ;
prefix += "" + PhoneListener.incoming;
String suffix = "";
int audioformat = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_FORMAT, "1"));
switch (audioformat) {
case MediaRecorder.OutputFormat.THREE_GPP:
suffix = ".3gpp";
break;
case MediaRecorder.OutputFormat.MPEG_4:
suffix = ".mpg";
break;
case MediaRecorder.OutputFormat.RAW_AMR:
suffix = ".amr";
break;
}
try {
return File.createTempFile(prefix, suffix, dir);
} catch (IOException e) {
Log.e("CallRecorder", "RecordService:makeOutputFile unable to create temp file in " + dir + ": " + e);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create temp file in " + dir + ": " + e, Toast.LENGTH_LONG);
t.show();
return null;
}
}
public void onCreate() {
super.onCreate();
recorder = new MediaRecorder();
Log.i("CallRecorder", "onCreate created MediaRecorder object");
}
#SuppressLint("ShowToast")
public void onStart(Intent intent, int startId) {
Log.i("CallRecorder", "RecordService:onStartCommand called while isRecording:" + isRecording);
if (isRecording) return;
Context c = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
Boolean shouldRecord = prefs.getBoolean(Preferences.PREF_RECORD_CALLS, false);
if (!shouldRecord) {
Log.i("CallRecord", "RecordService:onStartCommand with PREF_RECORD_CALLS false, not recording");
return;
}
int audiosource = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1"));
int audioformat = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_FORMAT, "1"));
recording = makeOutputFile(prefs);
if (recording == null) {
recorder = null;
return; //return 0;
}
Log.i("CallRecorder", "RecordService will config MediaRecorder with audiosource: " + audiosource + " audioformat: " + audioformat);
try {
recorder.reset();
recorder.setAudioSource(audiosource);
Log.d("CallRecorder", "set audiosource " + audiosource);
recorder.setOutputFormat(audioformat);
Log.d("CallRecorder", "set output " + audioformat);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
Log.d("CallRecorder", "set encoder default");
recorder.setOutputFile(recording.getAbsolutePath());
Log.d("CallRecorder", "set file:" + recording);
recorder.setOnInfoListener(this);
recorder.setOnErrorListener(this);
try {
recorder.prepare();
} catch (java.io.IOException e) {
Log.e("CallRecorder", "RecordService:onStart() IOException attempting recorder.prepare()\n");
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to start recording: " + e, Toast.LENGTH_LONG);
t.show();
recorder = null;
return; //return 0; //START_STICKY;
}
Log.d("CallRecorder", "recorder.prepare() returned");
recorder.start();
isRecording = true;
Log.i("CallRecorder", "recorder.start() returned");
updateNotification(true);
} catch (java.lang.Exception e) {
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to start recording: " + e, Toast.LENGTH_LONG);
t.show();
Log.e("CallRecorder", "RecordService:onStart caught unexpected exception", e);
recorder = null;
}
return;
}
public void onDestroy() {
super.onDestroy();
if (null != recorder) {
Log.i("CallRecorder", "RecordService:onDestroy calling recorder.release()");
isRecording = false;
recorder.release();
long length = recording.length();
length = length / 1024;
Log.v("call", "pathh" + recording.getAbsolutePath() + length + "KB");
if (length == 0) {
Log.v("sizeeee", "settings");
Toast.makeText(getApplicationContext(), "change the audio source settings", Toast.LENGTH_LONG).show();
recording.delete();
Log.v("file", "delete");
}
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder finished recording call to" + recording, Toast.LENGTH_LONG);
t.show();
}
updateNotification(false);
}
// methods to handle binding the service
public IBinder onBind(Intent intent) {
return null;
}
public boolean onUnbind(Intent intent) {
return false;
}
public void onRebind(Intent intent) {
}
private void updateNotification(Boolean status) {
Context c = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
if (status) {
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Recording call " + prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1");
//CharSequence tickerText = "Recording call " + prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1");
long when = System.currentTimeMillis();
//Notification notification = new Notification(icon, tickerText, when);
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "CallRecorder Status";
CharSequence contentText = "Recording call...";
Intent notificationIntent = new Intent(this, RecordService.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(RECORDING_NOTIFICATION_ID, notification);
} else {
mNotificationManager.cancel(RECORDING_NOTIFICATION_ID);
}
}
// MediaRecorder.OnInfoListener
public void onInfo(MediaRecorder mr, int what, int extra) {
Log.i("CallRecorder", "RecordService got MediaRecorder onInfo callback with what: " + what + " extra: " + extra);
isRecording = false;
}
// MediaRecorder.OnErrorListener
public void onError(MediaRecorder mr, int what, int extra) {
Log.e("CallRecorder", "RecordService got MediaRecorder onError callback with what: " + what + " extra: " + extra);
isRecording = false;
mr.release();
}
}
You would have to create a a broadcastreceiver. The receiver detects if an call is incoming or outgoing. There you can record your calls. Use TelephonyManager Class. And add permissions in the manifest.
In the link is a basic description with source-code download:
http://www.devlper.com/2010/08/detecting-incoming-and-outgoing-calls-in-android/
If you get that working, you just would have to create a Dictionary(HashMap). There you could set the dictionary-key to save numbers and a key-value for incoming or outgoing calls.
Get familiar with custom ListView to create a ListView with an image.
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Create 2 images, incoming and outgoing. Lopp through your dictionary and set the images right.
Greets
According to my understanding, unregisterListener() should do the trick and I should stop getting updates from the sensors. However, this is not working. I've tried moving on to the applications menu, as well as opening another application and turning the screen off. Nothing makes the updates from the sensors stop. My code is as follows: I am trying to unregister the listeners in the onPause() and unregisterSensors() function.
public class MainActivity extends Activity implements SensorEventListener,
LocationListener {
private Location location;
private int lat, lng;
private LocationManager locationManager;
private String provider;
private SensorManager senSensorManager;
private Sensor senAccelerometer;
private Sensor senGyroscope;
private Sensor senMagneticField;
private float last_x, last_y, last_z;
private float gy_x, gy_y, gy_z;
private float mag_x, mag_y, mag_z;
private Button button;
int toggle = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("MainActivity", "In the main activity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
button = (Button) findViewById(R.id.btnButton1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
toggle++;
if ((senSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null
&& (location != null)) {
if (toggle % 2 == 0) {
button.setText("Stop");
registerSensors();
}
else {
unregisterSensors();
}
}
}
});
}
public void unregisterSensors() {
Log.i("MainActivity", senSensorManager.toString());
senSensorManager.unregisterListener(this);
locationManager.removeUpdates(this);
button.setText("Start");
Log.i("MainActivity", senSensorManager.toString());
}
public void registerSensors() {
senAccelerometer = senSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senGyroscope = senSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
senMagneticField = senSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
senSensorManager.registerListener(this, senAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senMagneticField,
SensorManager.SENSOR_DELAY_NORMAL);
/* DEBUG!! */onLocationChanged(location);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor mySensor = sensorEvent.sensor;
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
last_x = sensorEvent.values[0];
last_y = sensorEvent.values[1];
last_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = (new Date()).toString() + " x:" + last_x
+ " y:" + last_y + " z:" + last_z;
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
if (mySensor.getType() == Sensor.TYPE_GYROSCOPE) {
gy_x = sensorEvent.values[0];
gy_y = sensorEvent.values[1];
gy_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = ("Gyroscope x:" + gy_x + " y:" + gy_y + " z:" + gy_z);
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
if (mySensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mag_x = sensorEvent.values[0];
mag_y = sensorEvent.values[1];
mag_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = ("Magnetic Field x:" + mag_x + " y:" + mag_y
+ " z:" + mag_z);
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
}
protected void onPause() {
super.onPause();
senSensorManager.unregisterListener(this);
locationManager.removeUpdates(this);
}
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senMagneticField,
SensorManager.SENSOR_DELAY_NORMAL);
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
float speed = location.getSpeed();
Context context = getApplicationContext();
CharSequence text = (new Date()).toString() + " Lat:" + lat + " Long:"
+ lng + " Speed:" + speed;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
public void onProviderDisabled(String arg0) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It could be because the application is still running in the background, because it may not be dead yet.
i got this gps method:
// GPS
private void addGPSListener() {
globalconstant.db.setVersion(1);
globalconstant.db.setLocale(Locale.getDefault());
globalconstant.db.setLockingEnabled(true);
final String gps =
"CREATE TABLE IF NOT EXISTS GPS_Values ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 8), Longitude float(10, 8),Accuracy INTEGER,Speed INTEGER,City TEXT,timestamp TIMESTAMP);";
globalconstant.db.execSQL(gps);
Log.d("FESTIVALE :: ", "Frissítési idő: "
+ globalconstant.gps_update_value);
float f = Float.valueOf(globalconstant.gps_update_value.trim())
.floatValue();
float update = f * 1000;
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocListener = new MyLocationListener();
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 5f,
globalconstant.mlocListener);
// if(Global.getInstance().currentGPSLocation != null){
//
// }
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
float szel = (float) loc.getLatitude();
float hossz = (float) loc.getLongitude();
int horiAcc = (int) (loc.getAccuracy());
// int speed=(int) ((loc.getSpeed()*3600)/1000); //sebesség km/h-ban
int speed = 0;
if (loc.hasSpeed()) {
speed = (int) ((loc.getSpeed() * 3600) / 1000); // sebesség
// km/h-ban
} else {
speed = 0;
}
String test = String.format("%.08f", szel);
String test2 = String.format("%.08f", hossz);
Geocoder geocoder = new Geocoder(main.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(szel, hossz,
1);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues gps_values = new ContentValues();
gps_values.put("Latitude", test);
gps_values.put("Longitude", test2);
gps_values.put("Accuracy", horiAcc);
gps_values.put("Speed", speed);
gps_values.put("City", city);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
gps_values.put("timestamp", dateFormat.format(date));
try {
globalconstant.db.beginTransaction();
globalconstant.db.insert("GPS_Values", null, gps_values);
globalconstant.db.setTransactionSuccessful();
} finally {
globalconstant.db.endTransaction();
}
Log.d("FESTIVALE :: ",
"Hely " + test + ", " + test2 + " , " + horiAcc + " , "
+ speed + " , " + city + ","
+ dateFormat.format(date));
// String Text = "My current location is: " + "Latitude = "
// + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();
// Toast.makeText(getApplicationContext(), "Hely" +test + "\n" +
// test2 + "\n" + horiAcc + "\n" +speed + "\n" +city,
// Toast.LENGTH_SHORT)
// .show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// show gps otions
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.cancel();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(main.this);
builder.setMessage("A GPS nincs aktiválva!\nAktiválja most?")
.setPositiveButton("Aktivál", dialogClickListener)
.setNegativeButton("Nem", dialogClickListener).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
/* This is called when the GPS status alters */
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.v(tag, "Status Changed: Out of Service");
Toast.makeText(main.this, "Status Changed: Out of Service",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v(tag, "Status Changed: Temporarily Unavailable");
Toast.makeText(main.this,
"Status Changed: Temporarily Unavailable",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
Log.v(tag, "Status Changed: Available");
Toast.makeText(main.this, "Status Changed: Available",
Toast.LENGTH_SHORT).show();
break;
}
}
public void onGpsStatusChanged(int event) {
if (event == GpsStatus.GPS_EVENT_FIRST_FIX) {
// showMessageDialog("GPS fixed");
Toast.makeText(getApplicationContext(), "GPS fixed",
Toast.LENGTH_SHORT).show();
}
}
}// gps vége
I want to make a simple loader dialog until it's connected to the satellite.
How can i manage that? how can i check that it connected to the satellite first before this method is called?
Thanks for your answers!
You need to implement GpsStatus.Listener for this.
for example,
public class MyActivity extends Activity implements GpsStatus.Listener
{
...
...
...
// add listener into locationManager
locationManager.addGpsStatusListener(this);
#Override
public void onGpsStatusChanged(int)
{
switch (event)
{
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
break;
case GpsStatus.GPS_EVENT_FIRST_FIX: // this means you found GPS Co-ordinates
break;
case GpsStatus.GPS_EVENT_STARTED:
break;
case GpsStatus.GPS_EVENT_STOPPED:
break;
}
}
}
You can pop up the dialog, request location updates and then dismiss the dialog when you actually get a location update.
Have your Activity implement GpsStatus.Listener
then use:
public void onChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
break;
case GpsStatus.GPS_EVENT_STARTED:
break;
case GpsStatus.GPS_EVENT_STOPPED:
break;
}
}
GpsStatus.GPS_EVENT_FIRST_FIX is the event sent when the GPS system has received its first fix since starting.
i got this gps reciever method, which store's some data into a database.
// GPS
private void addGPSListener() {
globalconstant.db.setVersion(1);
globalconstant.db.setLocale(Locale.getDefault());
globalconstant.db.setLockingEnabled(true);
final String gps =
"CREATE TABLE IF NOT EXISTS GPS_Values ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 8), Longitude float(10, 8),Accuracy INTEGER,Speed INTEGER,City TEXT,timestamp TIMESTAMP);";
globalconstant.db.execSQL(gps);
float f = Float.valueOf(globalconstant.gps_update_value.trim())
.floatValue();
Log.d("FESTIVALE :: ", "Frissítési idő: "
+ f);
float update = f;
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocListener = new MyLocationListener();
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 0,
globalconstant.mlocListener);
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
float szel = (float) loc.getLatitude();
float hossz = (float) loc.getLongitude();
int horiAcc = (int) (loc.getAccuracy());
// int speed=(int) ((loc.getSpeed()*3600)/1000); //sebesség km/h-ban
int speed = 0;
if (loc.hasSpeed()) {
speed = (int) ((loc.getSpeed() * 3600) / 1000); // sebesség
// km/h-ban
} else {
speed = 0;
}
String test = String.format("%.08f", szel);
String test2 = String.format("%.08f", hossz);
Geocoder geocoder = new Geocoder(main.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(szel, hossz,
1);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues gps_values = new ContentValues();
gps_values.put("Latitude", test);
gps_values.put("Longitude", test2);
gps_values.put("Accuracy", horiAcc);
gps_values.put("Speed", speed);
gps_values.put("City", city);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
gps_values.put("timestamp", dateFormat.format(date));
try {
globalconstant.db.beginTransaction();
globalconstant.db.insert("GPS_Values", null, gps_values);
globalconstant.db.setTransactionSuccessful();
} finally {
globalconstant.db.endTransaction();
}
Log.d("FESTIVALE :: ", "Hely " + test + ", " + test2 + " , "
+ horiAcc + " , " + speed + " , " + city + "," + dateFormat.format(date));
// String Text = "My current location is: " + "Latitude = "
// + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();
// Toast.makeText(getApplicationContext(), "Hely" +test + "\n" +
// test2 + "\n" + horiAcc + "\n" +speed + "\n" +city,
// Toast.LENGTH_SHORT)
// .show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// show gps otions
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.cancel();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(main.this);
builder.setMessage("A GPS nincs aktiválva!\nAktiválja most?")
.setPositiveButton("Aktivál", dialogClickListener)
.setNegativeButton("Nem", dialogClickListener).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}// gps vége
the avarege update time is 1 sec. But my phone get's lagging (galaxy s2)i can see it because there's a chronometer.
Does anyone have any idea about why?
i think i got the solution:
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 0,
globalconstant.mlocListener);
after the 'update' it stands a '0'. and heres what i found:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
that means the min Distance was '0' so this is why it was so 'laggy'.
But thank you for anyone!
GPS is VERY processor intensive. It does not surprise me that your phone slows. This is not unusual.
In fact, if you leave the GPS on long enough your phone will get hot and the battery will drain very rapidly!
I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()