Android Broadcast in one Fragment - android

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

Related

Call a method inside onReceive

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

Sending data from bound Service's another thread to Activity

I have Activity and Service, which is called by bindService from Activity. In this service I perform some operations in another thread using Vk sdk. Here I parse json to my models and add them to list. My question is how can I send this list from another thread after parsing to my activity? Here is code of my service
public class RequestService extends Service {
private final IBinder mBinder = new RequestBinder();
private List<Item> mItems;
private String mStartFrom;
private VKRequest mVKRequest;
public class RequestBinder extends Binder {
public RequestService getService() {
return RequestService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
mItems = new ArrayList<>();
loadNews("");
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void loadNews(String startFrom) {
if (startFrom.equals("")) {
mItems.clear();
}
mVKRequest = new VKRequest(Constants.METHOD_NAME, VKParameters.from(Constants.FILTERS,
Constants.FILTER_NAMES, VKApiConst.COUNT, Constants.NEWS_COUNT, Constants.START_FROM,
startFrom));
// this performs in another thread
mVKRequest.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
JSONObject result = response.json;
try {
mItems = ParseUtils.parse(result);
mStartFrom = ParseUtils.getNextFrom();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public List<Item> getItems() {
return mItems;
}
public String getStartFrom() {
return mStartFrom;
}
}
You can use context.sendBroadcast(intent). From any class in your project you can create an Intent and send this intent through broadcast.
For example:
// Somewhere in your code (your service class, for example)
private void sendMessage(Context context) {
Intent intent = new Intent("com.example.keys.MESSAGE");
intent.putExtra("message", "Hello World!");
// Send Broadcast to Broadcast receiver with message
context.sendBroadcast(intent);
}
In your activity, you need to declare a broadcast receiver:
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getExtras().getString("message"); // Contains "Hello World!"
// !!! Do something with your message !!!
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
registerReceiver(mHandleMessageReceiver, new IntentFilter("com.example.keys.MESSAGE"));
}
#Override
protected void onDestroy() {
unregisterReceiver(mHandleMessageReceiver);
}
So, you can send strings, numbers and objects from anywhere in your code. And you can have more than one BroadcastReceiver.

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.

Creating my own action for BroadcastReceiver

I have an method like this:
public static boolean checkConnection(){
if(getConnection()!=null){
return true;
}else
return false;
}
I trying to listen to the result of this method throughout my application. Till my application is alive. Only inside my application
How should I create my own action so that in BroadcastReceiver I can listen to this method and show an dialog when it returns false and hide the dialog automatically when it start returning true?
How and what will be the best approach to do this?
public class BroadCastActivity extends Activity implements OnClickListener{
ConnectionReceverLocal mReceverLocal;
Button mSwithcOn,mSwitchOff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broad_cast);
/*Intent intent = new Intent();
intent.setAction("com.broadcast.myconnectionbroadcast");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);*/
mReceverLocal = new ConnectionReceverLocal();
mSwitchOff = (Button)findViewById(R.id.switchoff);
mSwithcOn = (Button)findViewById(R.id.switchon);
mSwitchOff.setOnClickListener(this);
mSwithcOn.setOnClickListener(this);
}
private void sendMessage() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("Connection result Checking Asynctasks", ""+ConnectionProvider.checkConnection());
return ConnectionProvider.checkConnection();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Intent intent = new Intent("com.broadcast.myconnectionbroadcast");
// Add data
intent.putExtra("message", result);
LocalBroadcastManager.getInstance(BroadCastActivity.this).sendBroadcast(intent);
}
}.execute();
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceverLocal);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mReceverLocal,
new IntentFilter("com.alignminds.broadcast.myconnectionbroadcast"));
sendMessage();
}
public class ConnectionReceverLocal extends BroadcastReceiver {
public ConnectionReceverLocal() {
}
#Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder mDBuilder = new AlertDialog.Builder(BroadCastActivity.this);
Boolean intentAction = intent.getBooleanExtra("message", false);
if(intentAction==false)
{
Log.d("Connection is false in broadcast recever", "Connection is false");
if(mDBuilder!=null)
{
mDBuilder.setMessage("No Network");
mDBuilder.create().show();
}
}else {
Log.d("Connection is true in broadcast recever", "Connection is true");
if(mDBuilder!=null)
{
mDBuilder.setMessage("Network Ok");
mDBuilder.create().show();
}
}
}
}
#Override
public void onClick(View v) {
if(v==mSwithcOn)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
if(v==mSwitchOff)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}
}
Send a broadcast with whatever action you want like this
Intent intent = new Intent();
intent.setAction("my_fancy_action");
intent.putExtra(EVENT_MESSAGE, message);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Subclass BroadcastReceiver class to listen for broadcasts
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
// Do something
}
Register your receiver to listen to the broadcast
IntentFilter filter = new IntentFilter();
filter.addAction("my_fancy_action");
LocalBroadcastManager.getInstance(context).registerReceiver(myReceiver, filter);

android: how to get broadcasted messages from service when activity is in background

I have a service and an activity. in service I broadcast messages received from network and in the activity show these messages. this works fine. but all messages will lost when the activity is in the background.
How can I get last messages(if exists) from server, in activity onResume(or onCreate)?
EDIT :
in service:
public class server extends Service implements Runnable
{
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onStart(Intent intent, int startID)
{
//initializing socket and begining listen
new Thread(this).start();
}
public void run()
{
String readed;
while (true)
{
if(reader == null) continue;
try
{
if ((readed = reader.readLine()) != null)
{
Intent intent = new Intent(SEND_DATA_INTENT);
intent.putExtra("type", "message");
intent.putExtra("content", readed.substring(1));
sendBroadcast(intent);
Thread.sleep(100);
}
}
catch (Exception ee) { }
}
}
}
and in activity:
public class menhaj extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
#Override
protected void onResume()
{
if (dataUpdateReceiver == null) dataUpdateReceiver = new DataReciver();
IntentFilter intentFilter = new IntentFilter(server.SEND_DATA_INTENT);
registerReceiver(dataUpdateReceiver, intentFilter);
super.onResume();
};
#Override
protected void onPause()
{
if (dataUpdateReceiver != null) unregisterReceiver(dataUpdateReceiver);
super.onPause();
};
private class DataReciver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(server.SEND_DATA_INTENT))
{
Bundle bdl = intent.getExtras();
String type = bdl.getString("type");
if (type.equals("message"))
{
String message = bdl.getString("content");
db.addMessage(message);
showMessage(message);
}
}
}
}
}
If that activity is in the background, the user probably doesn't want to see messages from it. Show notifications from your services instead. Generally, an activity should de-register itself onPause() and register again onResume() when it comes back to the foreground.
I would declare BroadcastReceivers , those can receive messages and bring back to from your avtivity / app

Categories

Resources