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
Related
is is possible to set own context after creating broadcastreceiver like this:?
public class MyFragment extends Fragment(){
Button myButton;
#Override
onCreate {
myButton = (Button) findview...
myButton.setOnClickListner(myListener);
}
.
.
.
MyListener {
#Override
OnClickListner {
MyBroadCastReceiver receiver = new MyBroadCastReceiver()
receiver.setContext(mContext)
}
}
public static class MyBroadcastReceiver extends BroadcastReceiver {
Context mContext;
void setContext(Context context) {
mContext = context;
}
#Override
public void onReceive(Context context, Intent intent) {
if (mContext!= null){
log.d(TAG, "Context not null")
}
}
}
Every time method onReceive is invoked my mContext is null, is there any solution for that?
try this my friend
public class MyReceiver extends BroadcastReceiver {
Context mContext;
public MyReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (mContext != null) {
log.d(TAG, "Context not null")
}else{
log.d(TAG, " null Context ")
}
}
}
create new object of your broadcast like this
MyReceiver receiver = new MyReceiver(this);
The problem was with declaring receiver in manifest, while it should be declared only in fragment, after changing it, everything works as it should.
Thanks for help.
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();
}
}
}
This questions is similiar to How to use getApplicationContext in BroadcastReceiver class?.
But i didn't know how is the previous activity of his doing. So i didn't know how to resolve mine.
This is my activity :
public class backgroundApplication extends Activity {
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.background_application);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(backgroundApplication.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(backgroundApplication.this, 0, alarmIntent, 0);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel();
}
});
findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAt10();
}
});
}
for the complete code, i've got it from here : http://javatechig.com/android/repeat-alarm-example-in-android
And this is my AlarmReceiver.class extends BroadCastReceiver implements IndoorAtlasListener :
public class AlarmReceiver extends BroadcastReceiver implements IndoorAtlasListener
{
#Override
public void onReceive(Context context, Intent intent) {
initIndoorAtlas();
}
private void initIndoorAtlas() {
try {
mIndoorAtlas = IndoorAtlasFactory.createIndoorAtlas(
getApplicationContext, // this is the redline
this, // IndoorAtlasListener
mApiKey,
mApiSecret);
} catch (IndoorAtlasException ex) {
Log.e("IndoorAtlas", "init failed", ex);
}
}
Anyone can help me ?
in you onReceive method
initIndoorAtlas(context);
and in method
private void initIndoorAtlas(Context context) {
try {
mIndoorAtlas = IndoorAtlasFactory.createIndoorAtlas(
context, // this is the redline
this, // IndoorAtlasListener
mApiKey,
mApiSecret);
} catch (IndoorAtlasException ex) {
Log.e("IndoorAtlas", "init failed", ex);
}
}
If method is form implementing interface then use this code..
private Context context:
and onReceive Method
this.context = context;
and in you method use context as it is global variable we can access it.
I want custom calling screen I have achieved that but problem is that my screen is not going back when call cuts.i(..) want to terminate screen when call cuts. My code is:
public class receiver_Call extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
Thread pageTimer = new Thread(){
public void run(){
try{
sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
} finally {
//Toast.makeText(context," text", 5).show();
Intent i = new Intent();
i.setClass(context, My_call_receiver.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
};
pageTimer.start();
}
}
Have you tried a listener for when the call ends:
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
And in your Listener:
private class EndCallListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {}
if(TelephonyManager.CALL_STATE_IDLE == state) {}
}
}
EndCallListener is your class which extends PhoneStateListener (which is defined above)
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);
}
...
}