Call a method inside onReceive - android

Not able to call cameraImage() method inside onReceive().
private BroadcastReceiver dataReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent i) {
Log.e("Data", "Service Recieved");
responseString = i.getStringExtra(DataRequest.EXTENDED_DATA_STATUS);
textView.setText(responseString);
if (Float.parseFloat(responseString) < 100) {
cameraImage();
}
}
};
cameraImage() is written in the same activity
public void cameraImage(){
camera.takePicture(null, null, jpegCallback);
}

Related

Android Broadcast in one Fragment

I'm building my own VoIP app. Originally use Activity and BroadcastReceiver and it works fine, now I want to convert them to Fragment for my drawer.
Because BroadcastReceiver cannot use by Fragment, so I find some methods on stackoverflow but still not work...
All the code below is in the same file
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
V = inflater.inflate(R.layout.dial, container, false);
filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(callReceiver, filter);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
// Inflate the layout for this fragment
return V;
}
private final BroadcastReceiver callReceiver = new BroadcastReceiver()
{
#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();
}
}
public void onCallEnded(SipAudioCall call) {
endMessage();
}
};
incomingCall = manager.takeAudioCall(intent, listener);
updateStatus("call incoming");
call = incomingCall;
call.answerCall(30);
call.startAudio();
call.setSpeakerMode(isSpeakerClicked);
} catch (Exception e) {
if (incomingCall != null) {
incomingCall.close();
}
}
}
};
In your Fragment :
Call registerBroadcast() in your onCreateView
private void registerBroadcast() {
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(addCallReceiver,
new IntentFilter(getString(R.string.broadcast_add_call)));
}
BroadcastReceiver addCallReceiver= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// perform actions
}
};
From where you want to trigger receiver :
LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent(getString(R.string.broadcast_add_call)));

LocalBroadcastManager not receiving broadcasts in a Activity

I am using a LocalBroadcastManager to make broadcast to my activtiy and services using APPLICATION CONTEXT , like this:
public class CommonForApp extends Application{
public void broadcastUpdateUICommand(String[] updateFlags,
String[] flagValues) {
Intent intent = new Intent(UPDATE_UI_BROADCAST);
for (int i = 0; i < updateFlags.length; i++) {
intent.putExtra(updateFlags[i], flagValues[i]);
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
mLocalBroadcastManager.sendBroadcast(intent);
}}
Now Using a Listener in my Service, I am calling broadcastUpdateUICommand() ,like this:
public class mService extends Service {
public BuildNowPLaylistListListener buildCursorListener = new BuildNowPLaylistListListener() {
#Override
public void onServiceListReady() {
mApp.broadcastUpdateUICommand(
new String[] { CommonForApp.INIT_DRAWER},
new String[] {""});
}}}
And i am receiving the broadcast in my Activity, like this:
public class mActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mtoast.showtext("in onreceive"); //toast to check
if (intent.hasExtra(CommonForApp.INIT_DRAWER))
initialiseDrawer();
}};
}
mApp is instance of Application.
CommonForApp is my Application Class.
But in my activity i am not receving any broadcast(the broadcast manager is initialised using application context) .
Can Anyone suggest me why i am not receiving broadcast in my activity? ..
.Thanks in advance !
in activity:
protected BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(intent.hasExtra("type")){
// Do some action
}
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("data-loaded"));
}
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
then you send broadcast:
public static void sendBroadcastMessageDataLoaded(Context context, String dataType){
Intent intent = new Intent("data-loaded");
intent.putExtra("type", dataType);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

Unable to receive Broadcast

I am sending a Broadcast from my Service and trying to receive in my Activity but I don't see it receiving. Can someone suggest if I am doing something wrong. I am seeing onResume getting called but don't see flag
Log.d("InchooTutorial", msg_for_me);
getting logged.
Service Code :
Intent sendableIntent = new Intent("SOTGSAMReceiver");
sendableIntent.putExtra("kicked", prefs.getSurveySubmittedStatus(context));
LocalBroadcastManager.getInstance(AcrService.this).sendBroadcast(sendableIntent;
Activity Code :
// Get Broadcast
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("InchooTutorial", "Inside onResume");
IntentFilter intentFilter = new IntentFilter("SOTGSAMReceiver");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// extract our message from intent
String msg_for_me = intent.getStringExtra("kicked");
// log our message value
Log.d("InchooTutorial", msg_for_me);
}
};
// registering our receiver
this.registerReceiver(mReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
If you are using LocalBroadcastManager to send broadcast you need to register with it.
Write for register:
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);
And for unregister:
LocalBroadcastManager.getInstance(this).unregisterReceiver(this.mReceiver);
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.sixmod.com.sixmod.MyReceiver";
Intent bi = new Intent(COUNTDOWN_BR);
Intent ci = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(180000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
ci.putExtra("countdownFinish", 1);
sendBroadcast(ci);
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
In Activity
private BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.e("Receiver Registered", "Registered broacast receiver");
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(br);
Log.e("Unregistered", "Unregistered broacast receiver");
}
#Override
public void onStop() {
try {
getActivity().unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {// here you fetch the data

How to know when the services has ended

I want know when the service has ended, so I use BroadcastReceiver.
My service name is CheckNuevosAvisosIntentServices and I launch it in main.java (onCreate method) as:
Intent msgIntent = new Intent(Main.this, CheckNuevosAvisosIntentService.class);
msgIntent.putExtra("iteraciones", 1);
startService(msgIntent);
My manifest inside application tag.
<!-- Services -->
<service android:name="com.kirolm.instalacionesdep.services.CheckNuevosAvisosIntentService" />
In another fragment (HomeFragment) I use isMyServiceRunning method and BroadcastReceiver class:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (CheckNuevosAvisosIntentService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
My Broadcast code is this:
public class ProgressReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "The service is running...");
}
else if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "The service has been ended");
}
}
}
and in creathe method (HomeFragment) I implements this:
if(!isMyServiceRunning()){
Log.e("Testing", "HomeFragment: The service is running");
}else{
Log.e("Testing", "HomeFragment: The servie stop");
}
CheckNuevosAvisosIntentServicescode:
public class CheckNuevosAvisosIntentService extends IntentService{
public static final String ACTION_PROGRESO = "com.kirolm.instalacionesdep.services.action.PROGRESO";
public static final String ACTION_FIN = "com.kirolm.instalacionesdep.services.action.FIN";
public CheckNuevosAvisosIntentService() {
super("CheckNuevosAvisosIntentService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
int iter = intent.getIntExtra("iteraciones", 0);
for(int i=1; i<=iter; i++) {
Intent bcIntent = new Intent();
bcIntent.setAction(ACTION_PROGRESO);
bcIntent.putExtra("progreso", i*10);
sendBroadcast(bcIntent);
}
buscaNuevasNoticasRss();
Intent bcIntent = new Intent();
bcIntent.setAction(ACTION_FIN);
sendBroadcast(bcIntent);
}
private void buscaNuevasNoticasRss() {
// TODO Auto-generated method stub
//This method checks. When this method finish I want finish my services.
}
}
When buscaNuevasNoticiasRssfinish, I want finish my services.
I receive when the service is running but I don't receive when the service stop.
Edited: HomeFragment (onCreat method)
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ProgressReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Testing", "HomeFragment. BoradcastReceiver. Dentro de onReceive");
if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service is running...");
}
else if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service has been ended");
}
}
};
}
Override the onDestroy() method of your IntentService and send a broadcast to your receiver saying the service is destryed.
public class CheckNuevosAvisosIntentService extends IntentService{
//Your code
.......
.......
#Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent(CheckNuevosAvisosIntentService.ACTION_FIN));
}
}
And create a BroadcastReceiver as an inner class of HomeFragment.
private class HomeFramgnet extends Fragment {
private ProgressReceiver progressReceiver;
Override
public void onCreate(Bundle savedInstanceState) {
progressReceiver = new ProgressReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_PROGRESO);
intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_FIN);
registerReceiver(progressReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(progressReceiver);;
}
class ProgressReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Testing", "HomeFragment. BoradcastReceiver. Dentro de onReceive");
if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service is running...");
} else if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service has been ended");
}
}
}
}

Stop service in an activity

I'm using following code to stop my service
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
And this is my service that works indefinitely
public class UsageRecorderService extends IntentService {
public UsageRecorderService() {
super("UsageRecorder");
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
Why does not stop my service?
This code would work
public class UsageRecorderService extends IntentService {
private boolean mStop = false;
public UsageRecorderService() {
super("UsageRecorder");
}
public final Object sLock = new Object();
public void onDestroy() {
synchronized (sLock) {
mStop = true;
}
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
synchronized (sLock) {
if (mStop) break;
}
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
You can use stopService
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
Also I recommend to read Services guide to understand what is going there.
Activity:
sendBroadcast(new Intent(ACTION_STOP));
IntentService
public class UsageRecorderService extends IntentService {
private static final String TAG = "UsageRecorderService";
String ACTION_STOP = "com.xxx.UsageRecorderService.ACTION_STOP";
boolean stop;
public UsageRecorderService() {
super("UsageRecorder");
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
if (ACTION_STOP.equals(intent.getAction())) {
stop = true;
}
}
};
#Override public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(ACTION_STOP);
registerReceiver(receiver, intentFilter);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG,"onHandleIntent");
while (true && !stop) {
Log.i(TAG,"----running----");
//UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
#Override public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
An IntentService is designed to stop itself only when all the requests present in the work queue have been handled.Android stops the service after all start requests have been handled.

Categories

Resources