I want to create a widget which display a text message depending on the date. My problem is that i do not know how to detect when the system changes date.
My code:
public class AlarmReceiver extends BroadcastReceiver {
MediaPlayer mp = null;// Here int m,n;
#Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_DATE_CHANGED)) { // new
MainActivity().setSunrise();
Toast.makeText(context, "deteced date change", Toast.LENGTH_SHORT).show();
}
public class AlarmReceiver extends BroadcastReceiver {
int m,n;
#Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_DATE_CHANGED)) {
Toast.makeText(context, "deteced date change", Toast.LENGTH_SHORT).show();
}
}
}
Related
I understand that the question is most likely elementary, but I can not think of it myself.
I make a simple alarm clock, but I can not figure out how to make an alarm clock at the click of a button.
Here is the class with Broadcast:
public void onReceive(Context context, Intent intent) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtone = RingtoneManager.getRingtone(context.getApplicationContext(),notification);
ringtone.play();
And the button is in the main class.
1. define a interface in your Utility class.
2. implement this interface inside your Receiver.
3. stop alarm via calling method of interface.
private interface RingtoneHelper {
void stopRingtone();
}
class Utility {
public static RingtoneHelper ringtoneHelper;
}
public class YourReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
final Ringtone ringtone = RingtoneManager.getRingtone(context.getApplicationContext(),notification);
ringtone.play();
Utility.ringtoneHelper = new RingtoneHelper() {
#Override
public void stopRingtone() {
if(ringtone.isPlaying()) {
ringtone.stop();
}
}
};
}
}
// todo add click action for your button
if(Utility.ringtoneHelper != null) {
Utility.ringtoneHelper.stopRingtone();
}
I need to display status of connection on the screen. It seemed a simple task...
This is my receiver code below:
public class PowerConnectionReceiver extends BroadcastReceiver {
public PowerConnectionReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
String state;
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
state = "Charging";
Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
} else {
intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
state = "Not charging";
Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
}
}
}
How can i display my STATE var on screen textView. Can anybody help with it? Thanks!
You need to register a Callback. Create an Interface in PowerConnectionReceiver like:
public Interface NetworkStatusCallback {
public void onStateChange(String state);
}
Now implement this Callback in your MainActivity like:
public class MainActivity extends AppCompatActivity implements PowerConnectionReceiver.NetworkStatusCallback {...}
Create a reference of this Callback in PowerConnectionReceiver and declare it like:
private NetworkStatusCallback mCallback;
mCallBack = (NetworkStatusCallback)context;
Now in onReceive(Context context, Intent intent) do this:
#Override
public void onReceive(Context context, Intent intent) {
String state;
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
state = "Charging";
mCallback.onStateChange(state);
Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
} else {
intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
state = "Not charging";
mCallback.onStateChange(state);
Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
}
}
You will receive state in MainActivity
I want my activity class to receive an intent from broascast Receiver (example START_TALKING, STOP_TALKING). And when I receive that intent, I want to check what action was being passed. How can I do this. My receiver is in separate class, it's public.
Here's my code
public void onReceive(Context context, Intent intent)
{
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HEADSETHOOK:
if (action == KeyEvent.ACTION_DOWN)
// here I want to notify my activity class (e.g. startActivity? I don't know)
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
// here I want to notify my activity class (e.g. startActivity? I don't know)
}
}
}
I really need your help guys tnx.
Here is my solution, in my project, hope it'll help you:
you should type this:
// put your action string in intent
Intent intent = new Intent("com.example.myproject.ADD_ITEM_BASKET");
// start broadcast
activity.sendBroadcast(intent);
public class Myclass extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// creating and register receiver
Receiver receiver = new Receiver();
IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");
getActivity().registerReceiver(receiver, intentFilterAdd);
getActivity().registerReceiver(receiver, intentFilterDelete);
}
// your receiver class
class Receiver extends BroadcastReceiver
{
// catch messages from intent
#Override
public void onReceive(Context context, Intent intent) {
if("com.example.myproject.ADD_ITEM_BASKET".equals(intent.getAction().toString()))
{
// do something
}
else if("com.example.myproject.DELETE_ITEM_BASKET".equals(intent.getAction().toString()))
{
// do something
}
}
}
}
You can use putExtra() in your BroadcastReceiver's onReceive().
/**
* #author Skylifee7 on 23/06/2017.
* TemplateResultReceiver.java
*/
public class TemplateResultReceiver extends BroadcastReceiver {
private static final String TAG = "BleshTemplate";
public static final String EXTRA_MESSAGE = "TRANSACTION_MESSAGE";
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (intent.getAction().equals(BleshConstant.BLESH_TEMPLATE_RESULT_ACTION)) {
String actionType = intent.getStringExtra(BleshConstant.BLESH_ACTION_TYPE);
String actionValue = intent.getStringExtra(BleshConstant.BLESH_ACTION_VALUE);
if (actionType != null && actionValue != null) {
switch (actionType) {
case "MENU": sendMessage(actionValue);
/*
You may want to increase the case possibilities here, like below:
case: "ADMOB"
case: "VIRTUAL_AVM"
case: "SMART_CAR_KEY"
*/
default: sendMessage(actionValue);
}
}
}
}
private void sendMessage(String actionValue) {
Intent intent = new Intent(mContext.getApplicationContext(),TransactionActivity.class);
intent.putExtra(EXTRA_MESSAGE, actionValue);
mContext.getApplicationContext().startActivity(intent);
}
}
And in your Activity class' onCreate() method:
/**
* #author Skylifee7 on 24/06/2017.
* TransactionActivity.java
*/
public class TransactionActivity extends AppCompatActivity {
private String bleshKey;
private String TAG = "Transaction_Activity";
private String amount;
private String isSuccessful; //may be cast to boolean type.
private double latitude, longitude;
private LocationRequest mLocationRequest;
protected GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
requestPermission();
initLocationService();
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
bleshKey = intent.getStringExtra(BleshTemplateResultReceiver.EXTRA_MESSAGE);
ImageButton paymentBtn = (ImageButton) findViewById(R.id.buttonPay);
final EditText editTextAmount = (EditText) findViewById(R.id.editTextAmount);
paymentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
amount = editTextAmount.getText().toString();
callApiService();
}
});
}
}
You have to register the receiver... Follow this example..
public class MyActivity extends Activity {
private BroadcastReceiver myBroadcastReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// your onreceive code here
}
});
...
public void onResume() {
super.onResume();
....
registerReceiver(myBroadcastReceiver, intentFilter);
}
public void onPause() {
super.onPause();
...
unregisterReceiver(myBroadcastReceiver);
}
...
}
I have a problem to stop a PhoneStateListener. I tried to use unregisterReceiver() but it didn't work. I did read the site and saw that I have to use LISTEN.NON but I am unable to do it.
My questions are the following :
1 - where do I have to put my "telephony.listen(listener, PhoneStateListener.LISTEN_NONE);" in my code ?
2 - do I have to use unregisterReceiver ?
My code is not easy to explain and quite long so I won't give all my code but just the main view.
In fact : I start a service from timer. This service register a BR
/* First one */
public class TmrSettingsCheck extends BroadcastReceiver
{
public void setTimer(long milli)
{ // setRepeating }
public void onReceive(Context context, Intent intent)
{
// Try to know if we have to start or stop the service
context.startService(new Intent(context, SvcCall.class));
OR
context.stopService(new Intent(context, SvcCall.class));
}
}
/* Second one */
public class SvcCall extends Service
{
private BroadcastReceiver br_call;
public void onCreate()
{ // Creation }
public int onStartCommand(Intent intent, int flags, int startId)
{
// register the broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBR(this._context);
this.registerReceiver(this.br_call, filter);
return (START_STICKY);
}
public class CallBR extends ClsCallReceiver
{
public CallBR(Context context)
{ // constructor }
protected void onIncomingCallStarted(String number, Date start)
{ // XYZ
}
protected void onIncomingCallEnded(String number, Date start, Date end)
{ // XYZ }
protected void onOutgoingCallStarted(String number, Date start)
{ // XYZ }
protected void onOutgoingCallEnded(String number, Date start, Date end)
{ // XYZ }
protected void onMissedCall(String number, Date start)
{ // XYZ }
}
public IBinder onBind(Intent intent)
{ return null; }
public void onDestroy()
{
this.unregisterReceiver(this.br_call);
super.onDestroy();
}
}
/* Third one */
public abstract class ClsCallReceiver extends BroadcastReceiver
{
public static PhonecallStartEndDetector listener;
String outgoingSavedNumber;
protected Context savedContext;
TelephonyManager telephony;
public void onReceive(Context context, Intent intent)
{
savedContext = context;
if (listener == null)
listener = new PhonecallStartEndDetector();
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL"))
{
listener.setOutgoingNumber(intent.getExtras().getString("android.intent.extra.PHONE_NUMBER"));
return;
}
this.telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
this.telephony.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
public class PhonecallStartEndDetector extends PhoneStateListener
{
public PhonecallStartEndDetector()
{ // XYZ }
public void onCallStateChanged(int state, String incomingNumber)
{ // XYZ }
}
protected abstract void onIncomingCallStarted(String number, Date start);
protected abstract void onOutgoingCallStarted(String number, Date start);
protected abstract void onIncomingCallEnded(String number, Date start, Date end);
protected abstract void onOutgoingCallEnded(String number, Date start, Date end);
protected abstract void onMissedCall(String number, Date start);
}
Use LISTEN_NONE as parameter to listen method to stop listening for updates. this will make the listener listen to none.
telephonymanager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE );
I want to use
context.sendBroadcast(intent, receiverPermission);
in my application
but I don't know to pass receiverPermission parameter in function and also how to set in manifest file
please any body help me
I want to show you my source code
public class LocationReceiver extends BroadcastReceiver {
public static final String BROADCAST_ACTION = "LOCATION_CHANGE";
#Override
public void onReceive(Context context, Intent intent) {
intent.setAction(BROADCAST_ACTION);
Bundle b = intent.getExtras();
Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
Logger.debug("Loc:"+loc);
if(loc != null){
doBroadCast(context,intent,loc);
}
}
public void doBroadCast(final Context context,final Intent i1,final Location loc){
Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Logger.debug("LocationReceiver->sendLocation update broadcast");
i1.putExtra("Latitude", loc.getLatitude());
i1.putExtra("Longitude", loc.getLongitude());
context.sendBroadcast(i1,null);
}
});
}
}
and on activity I have write
#Override
protected void onResume() {
registerReceiver(broadcastReceiver, new IntentFilter(LocationReceiver.BROADCAST_ACTION));
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
UpdateUI(intent);
}
};
private void UpdateUI(Intent i){
Double Latitude = i.getDoubleExtra("Latitude",0);
Double Longitude = i.getDoubleExtra("Longitude",0);
showMap(Latitude, Longitude);
}
Now my problem is when it sendbroadcast it execute infinitly doBroadcast function(), please help me to come out.
Check after intent.setAction(BROADCAST_ACTION); that the action is really set to BROADCAST_ACTION
Check if you have registered this BroadcastReceiver with the action BROADCAST_ACTION in the <intent-filter> ( if it is, then that s why you have that infinite loop)