How to define broadcast receiver class and phonestatechange class in mainactivity? - java

this is my phonestate class where im checking phone state change
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListener";
public void onCallStateChange(int state, String incomingNumber){
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
Log.v(TAG, incomingNumber);
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "RINGING");
break;
} }
this is my broadcast receiver class where connecting with broadcast
public class CustomBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phoneNr= bundle.getString("incoming_number");
Log.v(TAG, "phoneNr: "+phoneNr);
}
how do define this in main activity?

Include this in your android manifest
<uses-permission android name="android.permission.READ_PHONE_STATE" />
If you want to listen phone state in your activity than use this instead of BroadcastReceiver class. Include This in your activity :
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener listener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
See this.

Just put it in your Activity, like:
private CustomBroadcastReceiver receiver = new CustomBroadcastReceiver();
Then add to OnCreate()
registerReceiver(receiver, new IntentFilter(YPUR_ACTION));
But there is no sense in putting TelephonyManager in BroadcastReceiver. You can just add it to your activity like in the answer above.

Related

How to start a video (Inside an activity) when a call is answered and stop the activity when the call is ended?

My code is working perfectly, i used a Brodcast Receiver.
In my application when the user click a button, a phone call is started, and the second activity (outcall.java) popup the screen, in the outcall Activity i have a VideoView, what I want to do is that the Video starts when the call is answered, and the activity is killed when the call is ended.
I have another problem with my code, i want the second activity to launch only when I use the button inside the application, because now it launches always even if i call a friend.
help will be appreciated
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
Button play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter(""));
play = (Button)findViewById(R.id.button2);
final MediaPlayer mP=MediaPlayer.create(MainActivity.this,R.raw.reco);
play.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (mP.isPlaying()){
mP.pause();
play.setBackgroundResource(R.drawable.play);
}else {
mP.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});
ActivityCompat.requestPermissions(this, new String[]{CALL_PHONE}, PackageManager.PERMISSION_GRANTED);
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
OpenCallOut();
}
};
public void OpenCallOut(){
Intent intent = new Intent(this, Outcall.class);
startActivity(intent);
}
public void CallButton(View view) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "123456"));
startActivity(intent);
}
#Override
public void onDestroy() {
finish();
System.exit(0);
}
}
Here is my Broadcast, i found this in codetoart but don't know how to use it
public class Broadcast extends BroadcastReceiver {
private static final String TAG = "PhoneStateBroadcastReceiver";
Context mContext;
String incoming_nr;
private int prev_state;
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent(""));
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phoneNr= bundle.getString("incoming_number");
Log.v(TAG, "phoneNr: "+phoneNr);
mContext=context;
}
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListener";
#Override
public void onCallStateChanged(int state, String incomingNumber){
if(incomingNumber!=null&&incomingNumber.length()>0) incoming_nr=incomingNumber;
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_STATE_RINGING");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_STATE_OFFHOOK");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_STATE_IDLE==>"+incoming_nr);
if((prev_state==TelephonyManager.CALL_STATE_OFFHOOK)){
prev_state=state;
}
if((prev_state==TelephonyManager.CALL_STATE_RINGING)){
prev_state=state;
}
break;
}
}
}
}
Here is my second activity Outcall.Java
public class Outcall1 extends AppCompatActivity {
VideoView myVideo;
private MediaController media_control;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outcall1);
myVideo = (VideoView) findViewById(R.id.videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myvideo);
media_control = new MediaController(this);
myVideo.setMediaController(media_control);
myVideo.setVideoURI(uri);
myVideo.start();
}
}
There are basically multiple ways for sending broadcasts in android.
In simple terms, some are due to system events such as the all the outgoing calls, while some are private to a particular application i.e the local broadcasts within the app.
1.In your case, the second activity is launching always because your onRecieve() is responding to system events. Hence you should try to sending local broadcast on the button click using the LocalBroadcastManager.sendBroadcast.
Alternatively , you can also use Service for starting your second activity .In this case , before starting call intent start your service .Inside the servie you can set a small delay and then start the second activity.
And for finishing your second activity on call end , you can use the above broadcast reciever that you posted but know for detecting call end, and then in case when the state of phone is call disconnected. Fire another broadcast to be recieved by the second activity which finishes the activity on recieving it.
This will help you with the implementation of the step 2.

pass data to broadcast receiver that already has intent filter coming from activity

when the phone is connected to the bluetooth in the car. I want my app to switch on automatically. to do this i have to save the paired car bluetooth device name to a string. then when the phones bluetooth is connected to something. I have to check if its the car. If it is i want to start a service.
I'm having difficulty passing the string that contains the bluetooth car device name to the receiver, as my receiver is already receiving a intent filter to listen out for ACTION_ACL_CONNECTED. is it possible to send a intent & an intent filter to the same receiver.
How can I can send the btdeviceName string from the activity to the receiver in this case.
Main Activity
private void addDrawerItems() {
final BroadcastReceiver bluetoothBroadcast = new BluetoothReceiver();
final IntentFilter blueToothFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
final Intent btbroadcastIntent = new Intent(this, BluetoothReceiver.class);
btbroadcastIntent.putExtra("btDeviceName", mPairedBluetoothDevice);
String[] osArray = {"Bluetooth Auto Start", "Reply to Calls", "Reply to sms", "Customise Message"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, osArray);
if (mIsPremiumUser) {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
} else {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Toast.makeText(getApplicationContext(), "blue", Toast.LENGTH_LONG).show();
showBluetoothDialog();
}
return true;
}
});
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView ctv = (CheckedTextView) view;
if (!mIsPremiumUser) {
Toast.makeText(getApplication(), "Upgrade", Toast.LENGTH_LONG).show();
return;
}
switch (position) {
case 0:
if (ctv.isChecked()) {
if (!isblueToothRegistered) {
registerReceiver(bluetoothBroadcast, blueToothFilter);
sendBroadcast(btbroadcastIntent);
isblueToothRegistered = true;
}
} else {
if (isblueToothRegistered) {
unregisterReceiver(bluetoothBroadcast);
isblueToothRegistered = false;
}
}
break;
BluetoothReceiver
public class BluetoothReceiver extends BroadcastReceiver {
private MainActivity ma;
private String pairedDevice;
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Receieved", Toast.LENGTH_LONG).show();
String action = intent.getAction();
pairedDevice = intent.getStringExtra("btDeviceName");
Toast.makeText(context, pairedDevice + "2", Toast.LENGTH_LONG).show();
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
Toast.makeText(context, "Bluetooth Connected", Toast.LENGTH_LONG).show();
if (device.getName().equals(pairedDevice)) {
Toast.makeText(context, device.getName() + " 1", Toast.LENGTH_LONG).show();
}
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Toast.makeText(context, "Bluetooth Disconnected", Toast.LENGTH_LONG).show();
}
}
}
An IntentFilter can have multiple actions. So start by creating your own custom action name to listen for and add it to the blueToothFilter.
blueToothFilter.addAction("my.custom.action");
Once you register the bluetoothBroadcast receiver with this IntentFilter it will now receive calls for both actions. Add another condition in onReceive to handle your new custom action.
Finally in your Activity send a broadcast with your custom action and the device name when ready.
Intent intent = new Intent()
.setAction("my.custom.action")
.putExtra("btDeviceName", mPairedBluetoothDevice);
sendBroadcast(intent);
UPDATE
I now understand that you want both the BluetoothDevice device and String pairedDevice in a single call to onReceive(). That is not possible since those variables are taken from separate actions and each action calls onReceive() once.
To fix this you can change the BluetoothReceiver to be an inner class of your Activityso you can keep a reference to the data you need there.

android - return data on change in a class instance

the goal is to have a class called CallReceiver that implements BroadcastReceiver
the class is listening for a call when there is a call it returns the caller number to the activity that created the instance.
example:
MainActivity:
CallReciver callreciver = new CallReciver(getApplicationContext());
CallReciver.java
public class CallReceiver extends BroadcastReceiver {
private Context mContext;
CallReceiver(Context context) {
this.mContext = context;
}
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Intent i = new Intent(mContext, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("callMsg", incomingNumber);
mContext.startActivity(i);
}
}
I tried to send an Intent with the number when a call has been detected, but the problem is that the intent starts the activity and init the variables, I need just to get the number.
requered result:
CallReceiver sends the number to MainActivity
Editing answer because your requirement was not clear at first.
if you want just the callers number in this receiver you might wanna try this snippet. Got this idea from this answer
How to get phone number from an incoming call?
In your manifest:
<receiver android:name=".ServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
In your reciever:
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
Intent i = new Intent(mContext, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("callMsg", incomingNumber);
mContext.startActivity(i);
}
},PhoneStateListener.LISTEN_CALL_STATE);
}

Class extending BroadcastReceiver not working

I made a helper class that extends BroadcastReceiver to listen for BluetoothDevice found and discovery finish intents. I have two activities which use this class by passing a handler. The handler receives messages as per the intent. I instantiate the class and registerReceiver like this:
From mainActivity:
deviceHelper=new DevicesHelper(myHandler,DevicesHelper.REQUEST_DETECT_DEVICES_IN_RANGE);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(deviceHelper, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(deviceHelper, filter);
if(myBluetoothAdapter.isDiscovering())myBluetoothAdapter.cancelDiscovery();
myBluetoothAdapter.startDiscovery();
From ListActivity:
deviceHelper=new DevicesHelper(deviceListHandler,DevicesHelper.REQUEST_DEVICE_LIST_ACTIVITY);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(deviceHelper, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(deviceHelper, filter);
DeviceHelper class:
public class DevicesHelper extends BroadcastReceiver {
public final static int REQUEST_DEVICE_LIST_ACTIVITY=1;
public final static int REQUEST_DETECT_DEVICES_IN_RANGE=2;
Handler myHandler;
int requestCode;
public DevicesHelper(){
}
public DevicesHelper(Handler handler,int requestCode){
this.requestCode=requestCode;
myHandler=handler;
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
// When discovery finds a device
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
switch(requestCode){
case REQUEST_DEVICE_LIST_ACTIVITY:
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//newDevicesCount++;
String[] deviceInfo={device.getName(),device.getAddress()};
myHandler.obtainMessage(DeviceListActivity.MESSAGE_NEW_DEVICE,deviceInfo);
};
break;
case REQUEST_DETECT_DEVICES_IN_RANGE:
String[] deviceInfo={device.getName(),device.getAddress()};
myHandler.obtainMessage(StripChartRecorder.MESSAGE_NEW_DEVICE,deviceInfo);
break;
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
myHandler.obtainMessage(StripChartRecorder.MESSAGE_DISCOVERY_FINISHED);
}
}
Handler:
private final Handler myHandler=new Handler() {
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_NEW_DEVICE:
doOtherStuff();
case MESSAGE_DISCOVERY_FINISHED:
dostuff();
}
break;
}}
Am I missing something here? I appreciate any help.
You need to sendMessage(Message msg) where msg is the Message you get with obtainMessage.
The problem was how I was handling the message received from the handler. Turned out Set<> was initially set to null as per eclipse's instruction, so it was never adding the devices received from the BroadcastReceiver helper class. I appreciate anyone who tried to help.

How to prevent automatic connection to WiFi

I try to prevent automatic connection to WiFi and displaying dialog box after turning on WiFi adapter from notification bar.
I register programmatically BroadcastReceiver that receives WIFI_STATE_CHANGED_ACTION. In WIFI_STATE_ENABLED I remove network from the configured network list. But it does not work.
I register BroadcastReceiver in:
#Override
protected void onStart() {
super.onStart();
registerReceiver(wifiStatusReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
}
And unregister in onStop method.
BroadcastReceiver code:
public class WiFiStatusReceiver extends BroadcastReceiver {
private WifiManager wifiManager;
#Override
public void onReceive(Context context, Intent intent) {
wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if(!isInitialStickyBroadcast()) { //it is not a sticky intent
switch(wifiManager.getWifiState()) {
case WifiManager.WIFI_STATE_ENABLING:
Toast.makeText(context, R.string.enabling_wifi, Toast.LENGTH_SHORT).show();
break;
case WifiManager.WIFI_STATE_ENABLED:
Toast.makeText(context, R.string.enabled_wifi, Toast.LENGTH_SHORT).show();
wifiManager.disconnect();
if(!wifiManager.getConfiguredNetworks().isEmpty()) { //there are some networks
for(WifiConfiguration wifiConfig :wifiManager.getConfiguredNetworks()) {
wifiManager.removeNetwork(wifiConfig.networkId);
}
}
break;
case WifiManager.WIFI_STATE_DISABLING:
Toast.makeText(context, R.string.disabling_wifi, Toast.LENGTH_SHORT).show();
break;
case WifiManager.WIFI_STATE_DISABLED:
Toast.makeText(context, R.string.disabled_wifi, Toast.LENGTH_SHORT).show();
break;
}
} else { //is a sticky intent
wifiManager.disconnect();
if(!wifiManager.getConfiguredNetworks().isEmpty()) { //there are some networks
for(WifiConfiguration wifiConfig :wifiManager.getConfiguredNetworks()) {
wifiManager.removeNetwork(wifiConfig.networkId);
}
}
}
}
}
Any suggestions ?
Try this to Disable the Wifi............. and when needed enable it.........
boolean isOn = false;
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(isOn);

Categories