how to get location in android debugging mode? - android

I am trying to get gps and network location in android. But every time I get location null.
LocationManager getting null in debugging mode.
Here is my Code
public class LocationService extends Service {
private static Timer timer = new Timer();
public Location mLocation;
#Override
public void onCreate() {
super.onCreate();
_startService();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void _startService() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
_serviceWork();
}
}, 1000, 30000);
}
private void _serviceWork() {
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mLocation.set(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
_shutdownService();
}
private void _shutdownService() {
if (timer != null) {
timer.cancel();
}
}
}

Related

android getContentResolver() order issue

project structure
I am trying to getContentResolver in MyLocationListenerActivity for accessing the data base which is implemented as LogContentProvider here. I have registered the MyLocationListenerActivity to the locationManager in MainActivity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void trackingServiceButtonOnClick(View v) {
startActivity(new Intent(MainActivity.this,
MyLocationListenerActivity.class));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListenerActivity myLocationListener = new MyLocationListenerActivity();
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, myLocationListener);
} catch (SecurityException e) {
Log.d("debug", e.toString());
}
if (getContentResolver() != null) {
Log.d("debug", "I can get content resolver");
}
}
and in MyLocationListenerActivity, If I want to getContentResolver() in onCreate(), that's fine, but If I try to getContentResolver in onLocationChanged, a error "get contentResolver() on a null object reference occurs", does anyone know why this happens?
public class MyLocationListenerActivity extends AppCompatActivity implements LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_location_listener);
// test() works fine here
test();
}
public void test() {
getContentResolver();
}
#Override
public void onLocationChanged(Location location) {
// error will happen here
test();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}

apps extremely slowing down while using broadcastreceiver to communicate with service android

in my app while i am making a communication between service and broadcastreceiver my apps extremely slowing down. if i use only service my apps running ok, but problem occurs when i try to show service's result through broadcast. below my code.
manifest:
<service
android:name=".ServiceClass_GetGps"
android:exported="false" />
broadcastreceiver :
public class FragmentMap extends Fragment implements OnMapReadyCallback{
double lat,lng;
GoogleMap googleMap=null;
public FragmentMap() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, null, false);
SupportMapFragment mapFragment=(SupportMapFragment)this.getChildFragmentManager().findFragmentById(R.id.map_FragmentMapId);
mapFragment.getMapAsync(this);
Intent intent=new Intent(getActivity(),ServiceClass_GetGps.class);
getActivity().startService(intent);
return view;
}
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter=new IntentFilter("imran");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver,intentFilter);
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
}
//broadcast receiver
private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
//String result=intent.getStringExtra("result");
// Toast.makeText(getActivity(), "Lat " +intent.getStringExtra("LAT") +" Lng "+intent.getStringExtra("LNG"), Toast.LENGTH_SHORT).show();
Handler handler=new Handler();
handler.post(new Runnable() {
#Override
public void run() {
context.startService(new Intent(context.getApplicationContext(),ServiceClass_GetGps.class));
if(intent.getStringExtra("LAT")!=null && intent.getStringExtra("LNG")!=null){
lat=Double.valueOf(intent.getStringExtra("LAT"));
lng=Double.valueOf(intent.getStringExtra("LNG"));
LatLng latLng=new LatLng(lat,lng);
if(googleMap!=null){
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
}else {
Toast.makeText(getActivity(),"Map is null",Toast.LENGTH_LONG).show();
}
}
}
});
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap=googleMap;
}
service class:
public class ServiceClass_GetGps extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener{
private HandlerThread handlerThread;
ServiceHandler serviceHandler;
LocalBroadcastManager localBroadcastManager;
private final static class ServiceHandler extends Handler {
public ServiceHandler(Looper looper){
super(looper);
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
#Override
public void onCreate() {
super.onCreate();
handlerThread=new HandlerThread("com.example.imranrana.datingapp");
handlerThread.start();
serviceHandler=new ServiceHandler(handlerThread.getLooper());
localBroadcastManager=LocalBroadcastManager.getInstance(this);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
final Handler handler=new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// Intent intent=new Intent("com.example.imranrana.datingapp");
// intent.putExtra("result","Imran");
// localBroadcastManager.sendBroadcast(intent);
handler.post(new Runnable() {
#Override
public void run() {
Intent intent1=new Intent("imran");
intent1.putExtra("LAT","23.8758448");
intent1.putExtra("LNG","90.3981515");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent1);
Toast.makeText(getApplicationContext(),"Service test",Toast.LENGTH_LONG).show();
}
});
handler.postDelayed(this,5000);
}
}).start();
return START_STICKY;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"apps stopped",Toast.LENGTH_LONG).show();
sendBroadcast(new Intent());
}
can anyone please solve my problem .
i just solved my problem by myself just removing restart command of service from broadcastreceiver . thanks

onReadyForSpeech calling multiple times while continuous Speech Recognition

I am creating an application in that i need continuous speech recognition. But onReadyForSpeech calling two times.
I am also attaching my code. Please help me to find out the problem.
Thanks in advance.
private SpeechRecognizer mSpeechRecognizer = null;
public static VoiceRecognizeService sVoiceRecognizeService;
private ITelephony mListener;
private boolean isListening;
private Intent mSaverController;
public VoiceRecognizeService() {
super();
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sVoiceRecognizeService = this;
startListening();
return START_NOT_STICKY;
}
public void setTelephonyListener(ITelephony mListener) {
this.mListener = mListener;
}
public static VoiceRecognizeService getInstance() {
return sVoiceRecognizeService;
}
// starts the service
public void startListening() {
if (!isListening) {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(this);
Intent mRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_IN");
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 2000);
mRecognizerIntent.putExtra("android.speech.extra.DICTATION_MODE", true);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, false);
mRecognizerIntent.putExtra("android.speech.extra.PREFER_OFFLINE", true);
mRecognizerIntent.putExtra("calling_package", this.getPackageName());
mSpeechRecognizer.startListening(mRecognizerIntent);
isListening = true;
}
}
public void processVoiceCommands(final ArrayList<String> partialData) {
}
public void restartListeningService() {
cancelSpeechRecognition();
startListening();
}
public void cancelSpeechRecognition() {
if (mSpeechRecognizer != null) {
mSpeechRecognizer.stopListening();
mSpeechRecognizer.cancel();
mSpeechRecognizer.destroy();
mSpeechRecognizer = null;
isListening = false;
}
}
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.e("VoiceError", "speechReady");
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float scale) {
if (mListener != null) {
mListener.onRmsChanged(scale);
}
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
if (i == SpeechRecognizer.ERROR_RECOGNIZER_BUSY) {
} else {
restartListeningService();
}
}
#Override
public void onResults(Bundle bundle) {
final ArrayList<String> data = bundle.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
if (data != null) {
processVoiceCommands(data);
}
restartListeningService();
}
#Override
public void onPartialResults(Bundle bundle) {
final ArrayList<String> data = bundle.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
Log.e("VoiceError", "partialResults " + data);
}
#Override
public void onEvent(int i, Bundle bundle) {
}
#Override
public void onDestroy() {
if (mSpeechRecognizer != null) {
mSpeechRecognizer.setRecognitionListener(null);
cancelSpeechRecognition();
}
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}

running an script only for an specific time

I have a code for detecting location that I want to works only for 2 minutes.
when I fire start() method script must works almost for 2 minutes.
problem is in there that how run my script only for an specific time.
I used this code but don't running correct.
don't fire stop() method from in Timer().schedule()
public class a implements LocationListener{
private LocationManager locationManager;
private String provider;
private Location lastloc;
private Context _context;
public a(Context context){
_context = context;
}
public void start(){
locationManager = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, (LocationListener) this);
new Timer().schedule(
new TimerTask(){
public void run() {
stop();
}
}
,System.currentTimeMillis(), 2*60*1000);
}
public void stop(){
Log.d("states","stop");
locationManager.removeUpdates((LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("states", "onLocationChanged()");
lastloc = location;
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
Check your code of Timer again. Usually, the Timer code should be like:
Timer.schedule(TimerTask,
delayTime); // delay a task before executed for the first time, in milliseconds
Because of your delayTime has been executed by using System.currentTimeMillis(), the System picks the current time in milliseconds since midnight, so that the TimerTask will be executed after millions millisecond.
Hence, use this code:
Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run() {
// do your thing here
}
}, 2*60*1000);
See this documentation about the type of Timer you created.
I finally solved my problem by using handlers.
read this page: Using Bundle Android to Exchange Data Between Threads
a.java
public class a implements LocationListener{
private LocationManager locationManager;
private String provider;
private Location lastloc;
private Context _context;
private Thread workingthread = null;
final Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
Log.d("states","return msg from timer2min");
if(msg.what==1){
stop();
}
super.handleMessage(msg);
}
};
public a(Context context){
_context = context;
}
public void start(){
locationManager = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, (LocationListener) this);
workingthread=new timer2min(mHandler);
workingthread.start();
}
public void stop(){
Log.d("states","stop");
locationManager.removeUpdates((LocationListener) this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("states", "onLocationChanged()");
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
timer2min.java
public class timer2min extends Thread {
private Handler hd;
public timer2min(Handler msgHandler){
hd = msgHandler;
}
public void run() {
try {
Thread.sleep(2*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = hd.obtainMessage();
msg.what = 1;
hd.sendMessage(msg);
}
}

How to display the value in the text field of Activity which is updated from service class?

This is my service class in that i increment the i value based on time...
public class BackService extends Service {
int i=0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
private void pollForUpdates() {
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("Service class called", "service class called "+i);
getRunningApps();
i++;
}
},0,1000);
}
private void getRunningApps()
{
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I want to append the i value to the TextView. i.e the TextView value is dynamically change based on i value...
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, BackService.class));
TextView tx=(TextView)findViewById(R.id.textView1);
}}
how to append the i value to tx...
Thank you in advance..
You will need to register Broadcast receiver for Sending data back from Service to Activity.see these usefull example for communication between Activity to service :
http://androidexperinz.wordpress.com/2012/02/14/communication-between-service-and-activity-part-1/
http://androidexperinz.wordpress.com/2012/02/21/communication-between-service-and-activity-part-2/
http://blog.philippheckel.com/2012/06/10/android-example-communication-between-activity-and-service-using-messaging/
Use this
public class MainActivity extends Activity {
TextView tx;
RefreshBroadcastReciver mBroadCastReciver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, BackService.class));
tx =(TextView)findViewById(R.id.textView1);
}
#Override
protected void onResume() {
super.onResume();
mBroadCastReciver = new RefreshBroadcastReciver();
registerReceiver(mBroadCastReciver, new IntentFilter("sendData"));
}
private class RefreshBroadcastReciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
tx.setText(intent.getIntExtra("i", 0)+"");
}
}
#Override
protected void onStop() {
super.onStop();
if(mBroadCastReciver!=null)
unregisterReceiver(mBroadCastReciver);
}
}
and your service is here
public class BackService extends Service {
int i=0;
Intent intent1;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
intent1=new Intent("sendData");
}
private void pollForUpdates() {
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("Service class called", "service class called "+i);
getRunningApps();
i++;
Message msg=new Message();
msg.arg1=i;
handler.sendMessage(msg);
}
},0,1000);
}
private void getRunningApps()
{
}
#Override
public void onDestroy() {
super.onDestroy();
}
protected Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
intent1.putExtra("i", msg.arg1);
sendBroadcast(intent1);
}
};
}

Categories

Resources