How to getApplcationContext using BroadCastReceiver - android

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.

Related

Activity has leaked IntentReceiver Error

before marking this post as closed or duplicate i want to say that i have done all the things that are mentioned on similar posts but none of them worked.
I have 2 receivers which i get data from. So i want to register the receivers when the activity starts and unregister them when the activity is not visible.
My Code:
public class MainActivity extends AppCompatActivity {
private CheckNetworkStatusReceiver checkNetworkStatusReceiver;
private CheckBatteryStatusReceiver checkBatteryStatusReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkConnection();
}
public void checkConnection() {
if(!ConnectionManager.isNetworkAvailable(MainActivity.this)){
ConnectionManager.wifiSettingsDialog(MainActivity.this).show();
}else{
registerReceivers();
}
}
public void registerReceivers() {
checkNetworkStatusReceiver = new CheckNetworkStatusReceiver();
checkBatteryStatusReceiver = new CheckBatteryStatusReceiver();
registerReceiver(checkNetworkStatusReceiver, new IntentFilter(Constants.INTENT_FILTER_CONNECTIVITY_CHANGE));
registerReceiver(checkBatteryStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
protected void onDestroy() {
super.onDestroy();
try{
unregisterReceiver(checkNetworkStatusReceiver);
unregisterReceiver(checkBatteryStatusReceiver);
}catch (Exception e){
e.printStackTrace();
}
}
#Override
protected void onResume() {
registerReceivers();
super.onResume();
}
#Override
protected void onRestart() {
registerReceivers();
super.onRestart();
}
#Override
protected void onStop() {
super.onStop();
try{
unregisterReceiver(checkNetworkStatusReceiver);
unregisterReceiver(checkBatteryStatusReceiver);
}catch (Exception e){
e.printStackTrace();
}
}
}
The receiver code:
public class CheckNetworkStatusReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null){
Log.e("Action ",intent.getAction());
if(intent.getAction().equalsIgnoreCase(Constants.INTENT_FILTER_CONNECTIVITY_CHANGE)) {
if (!ConnectionManager.isNetworkAvailable(context)){
Toast.makeText(context, R.string.no_internet, Toast.LENGTH_SHORT).show();
}
if (MobileDataManager.slowInternetConnection(context)){
Toast.makeText(context, R.string.slow_internet_delay, Toast.LENGTH_SHORT).show();
}
}
}
}
}
and the battery receiver:
public class CheckBatteryStatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null){
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
if (level <= 15){
Toast.makeText(context, "Batter level " + level + "% is very low. Please connect to a charger.", Toast.LENGTH_SHORT).show();
}
}
}
}
i get the error on the registerReceivers() method. Any ideas?
You register the receivers in onCreate() and then again in onResume(). This will leak the receivers that you registered in onCreate(), because you overwrite the variables you are using to hold references to them every time registerReceivers() is called.
This is not very robust code. You don't need to create new instances of the BroadcastReceiver every time. What you should do is to create one instance of each BroadcastReceiver in onCreate(). Then declare a boolean member variable in your class called receiversRegistered. In registerReceivers() you should check this boolean. If it is true, the receivers are already registered and you should do nothing. If not, register the receivers and then set the boolean to true. When you unregister the receivers, set the boolean to false.
EDIT: Here it is all done for you:
public class MainActivity extends AppCompatActivity {
private CheckNetworkStatusReceiver checkNetworkStatusReceiver;
private CheckBatteryStatusReceiver checkBatteryStatusReceiver;
private boolean receiversRegistered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkNetworkStatusReceiver = new CheckNetworkStatusReceiver();
checkBatteryStatusReceiver = new CheckBatteryStatusReceiver();
checkConnection();
}
public void checkConnection() {
if(!ConnectionManager.isNetworkAvailable(MainActivity.this)){
ConnectionManager.wifiSettingsDialog(MainActivity.this).show();
}else{
registerReceivers();
}
}
public void registerReceivers() {
// Only register if not already registered
if (!receiversRegistered) {
registerReceiver(checkNetworkStatusReceiver, new IntentFilter(Constants.INTENT_FILTER_CONNECTIVITY_CHANGE));
registerReceiver(checkBatteryStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
receiversRegistered = true;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (receiversRegistered) {
unregisterReceiver(checkNetworkStatusReceiver);
unregisterReceiver(checkBatteryStatusReceiver);
}
}
#Override
protected void onResume() {
registerReceivers();
super.onResume();
}
#Override
protected void onRestart() {
registerReceivers();
super.onRestart();
}
#Override
protected void onStop() {
super.onStop();
if (receiversRegistered) {
unregisterReceiver(checkNetworkStatusReceiver);
unregisterReceiver(checkBatteryStatusReceiver);
receiversRegistered = false;
}
}
}
Move the unregisterReceiver inside onPause not in onDestroy.
When your activity is moved in background onDestroy is not called. The activity is only paused. onDestroy is called when the app is closed manually or by the system.
(onPause is called before onDestroy in above situation)

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

Android get information from service

I made an service that triggers every 10 sec. How to connect service to activity when it triggers. Example i refresh my local DB, when appears an update Activity send an Toast.
AlarmService.class
#SuppressLint("SimpleDateFormat")
public class AlarmService extends Service {
Handler mHandler;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
}
public void f() {
Toast t = Toast.makeText(this, "Service is still running",
Toast.LENGTH_SHORT);
t.show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT);
t.show();
// TODO Auto-generated method stub
super.onStart(intent, startId);
mHandler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
f();
mHandler.postDelayed(this,10000);
}
};
mHandler.postDelayed(r, 10000);
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(this,AlarmService.class);
startService(serviceIntent);
}
}
Use broadcast receiver like this
public static class MyExtBroadcastReceiver extends BroadcastReceiver {
public MyExtBroadcastReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
//Call your activity here
}
Make a method for setting the alarm
public void setAlarm(){
f(); // call your method f() here
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
Intent alarmintent1 = new Intent(this, MyExtBroadcastReceiver.class);
PendingIntent sender1=PendingIntent.getBroadcast(this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
try {
am.cancel(sender1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
Calendar cal=Calendar.getInstance();
cal.add(Calendar.Seconds,10);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10*60, sender1);
Call this method from OnCreate()
#Override
public void onCreate() {
setAlarm();
}
}
You can use LocalBroadcastManager, Messenger, ResultReceiver to send data from service to Activity.
Here is an example that uses ResultReceiver to send updated data from Service to Activity.

Using Pending Intent

How to use pending intent to Toast something after a specified time when an app closes? Is there any other ways to do it?
I tried Broadcast receiver but don't know how to proceed.
public class Broad extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent i) {
// TODO Auto-generated method stub
i= new Intent(Intent.CATEGORY_HOME);
PendingIntent pi = PendingIntent.getBroadcast(c, 0, i, 0);
Toast.makeText(c, getResultData(), Toast.LENGTH_SHORT).show();
}
}
What to do next? Please help. I don't understand the tutorials as I'm new to android.
try this method:
public static void toastInTenSeconds(final Context context, final String text) {
new Thread(new Runnable() {
#Override
public void run() {
SystemClock.sleep(1000 * 10);
try {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// Do something
}
}
}
}
Call it from your Actvitiy onDestroy or onStop.

Start android activity from receiver (inside running service)

I want to display an alert when a sms is received, so my idea is to start a new activity that launch the alertdialog.
My service starts with no problem, and starts receiver as well..
I can receive sms and display toast alerts fine.. but i'd like to show a custom alertdialog instead.
This is the activity that starts my service (ServiceExampleActivity ):
public class ServiceExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStartService = (Button) findViewById(R.id.btnStart);
Button btnStopService = (Button) findViewById(R.id.btnStop);
btnStartService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StartMyService();
}
});
btnStopService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StopMyService();
}
});
}
private void StartMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
startService(myServiceIntent);
}
private void StopMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
stopService(myServiceIntent);
}
}
This is my Service (ServiceTest):
public class ServiceTest extends Service {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver myBroadcastReceiver = null;
#Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
this.myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
StartDialogActivity(context, intent);
}
};
this.registerReceiver(myBroadcastReceiver, theFilter);
}
#Override
public IBinder onBind(Intent arg) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("ServiceTest", "Started");
Toast.makeText(this, "Service started...", 3000).show();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
Toast.makeText(this, "Service destroyed...", 3000).show();
}
private void StartDialogActivity(Context context, Intent intent) {
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dlgIntent);
}
}
And this is the activity i want to launch to display the alertdialog normally..
public class DialogActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
}
}
When it tries to start the activity, the app crashes..
Can you tell me were is the error..??
Like this, you want start activity from service
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dlgIntent );

Categories

Resources