apps extremely slowing down while using broadcastreceiver to communicate with service android - 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

Related

Handler is not working at delay time in my background service

I have to perform some task continuously in MyService.java class. For this I use Handler but mHandler.postDelayed(this, 40000); is not getting fired after given time. It is getting fired after every second. Please help me out
public class SendMessageService extends Service {
private Handler mHandler = new Handler();
private Runnable task;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(stopReceiver, new IntentFilter("com.android.STOP_HANDLER"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
task = new Runnable() {
#Override
public void run() {
dosomething();
mHandler.postDelayed(this, 40000);
}
};
try {
mHandler.postDelayed(task, 40000);
} catch (Exception e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(stopReceiver);
}
private void dosomething() {
//perform my task
}
private BroadcastReceiver stopReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("receive","STOP");
mHandler.removeCallbacks(task);
}
};
}
I change my code to this and it is working
public class SendMessageService extends Service {
private Handler mHandler = new Handler();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(stopReceiver, new IntentFilter("com.android.STOP_HANDLER"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
mHandler.postDelayed(task, 40000);
} catch (Exception e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(stopReceiver);
}
private void dosomething() {
//perform my task
}
private BroadcastReceiver stopReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("receive","STOP");
mHandler.removeCallbacks(task);
}
};
private Runnable task = new Runnable() {
#Override
public void run() {
dosomething();
mHandler.postDelayed(this, 40000);
}
};
}

how to get location in android debugging mode?

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();
}
}
}

Start a service when activity is opened

How do i start a service when an activity is opened, I am using intent but the service isn't starting at all. Music is meant to be played when a certain page is opened, but no service is running at all.
This is the code i am using to start the service on the MainPage class.
public class BackgroundMusic extends Service implements Application.ActivityLifecycleCallbacks, Runnable {
MediaPlayer player;
private static final Handler uiHandler = new Handler(Looper.getMainLooper());
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.backgroundmusic);
player.setLooping(true);
player.setVolume(100, 100);
player.start();
Intent BackgrndMusic = new Intent(this, MainPage.class);
startService(BackgrndMusic);
getApplication().registerActivityLifecycleCallbacks(this);
}
#Override
public void onDestroy() {
super.onDestroy();
// stop listening for activities
getApplication().unregisterActivityLifecycleCallbacks(this);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onActivityStarted(Activity activity) {
// do not destroy this service
uiHandler.removeCallbacks(this);
}
#Override
public void onActivityStopped(Activity activity) {
// if an activity don't show up in 1 second, destroy this service
uiHandler.postDelayed(this, 1000);
}
#Override
public void run() {
// no more activity, destroy this service
stopSelf();
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
startService(BackgrndMusic);
}
#Override
public void onActivityResumed(Activity activity) {
Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
startService(BackgrndMusic);
}
#Override
public void onActivityPaused(Activity activity) {
Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
stopService(BackgrndMusic);
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
stopService(BackgrndMusic);
}
}
Use
#Override
protected void onResume()
{
super.onResume();
startService(foo);
}
#Override
protected void onDestroy()
{
super.onDestroy();
StopService(foo);
}

continue service working when the application closes

I have a simple Service
public class UpdateService extends Service {
private int seconds;
final static String MY_ACTION = "MY_ACTION";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
timer.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
final CountDownTimer timer = new CountDownTimer(86400000, 1000) {
public void onTick(long millisUntilFinished) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
Intent intent = new Intent();
intent.setAction(MY_ACTION);
sendBroadcast(intent);
}
public void onFinish() { }
};
}
When I close an application service stops working. But showing that the service is running.
What am I doing wrong?
Update
I changed CountDownTimer to Thread, but the problem remained
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
OnStart()
if(!t1.isAlive())
t1.start();
Because CountDown Timer is working only foreground means app is running and not minimized or closed. You have to place a Thread in Service that executing at particular time of you want.
try this :
public class LocalService extends Service
{
private static Timer timer = new Timer();
private Context ctx;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
ctx = this;
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
System.out.println("test");
}
};
}

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