how to use context inside the Broadcast Receiver?

孤街浪徒 提交于 2020-01-14 05:50:07

问题


I managed to create a function that returns context of an activity and I used this context inside a broadcast receiver and it does what it supposed to do, if the application is not stopped, but when I stop the application I cant get the context of the activity because it returns null value, so how can I maintain the context value to be used by the broadcast receiver even if my application gets killed ?

This is the function that returns the Context object and the constructor is called inside OnCreate() of the main activity:

public class ContextGen {
static Context conGen = null;

public ContextGen(Context context) {
    conGen = context;

}

public static Context returnContextGen() {

    return conGen;
}

}

and this is the broadcast receiver which checks for incoming SMS:

public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
@Override
    public void onReceive(Context context, Intent intent) {
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();
        // Context conOfMain = ContextGen.returnContextGen();

        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {

                SmsMessage currentMessage = SmsMessage
                        .createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage
                        .getDisplayOriginatingAddress();

                String senderNum = phoneNumber;
                String message = currentMessage.getDisplayMessageBody();

                // what i added to the code

                Log.i("SmsReceiver", "senderNum: " + senderNum
                        + "; message: " + message);

                // Show Alert
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, "senderNum: "
                        + senderNum + ", message: " + message, duration);
                toast.show();

                if (message.equalsIgnoreCase("PI lock")) {
                    System.out
                            .println("lock entereeeeed =====================");
                    Context conOfMain = ContextGen.returnContextGen();
                    System.out.println("Context is" + conOfMain);
                    LockDevice lock = new LockDevice(conOfMain);
                    lock.lockDeviceNow();
                    abortBroadcast();

    }}}}}

回答1:


Instead of doing it by the hard way as you are, just use a Singleton extending your Application. Something like this:

import android.app.Application;
import android.content.Context;

public class MyAppContext extends Application {
  private Context context;

  public Context getContext() { return context; }

  public void setContext(Context context_) { context = context_; }

  public void onCreate(){
    super.onCreate();
    this.context = getApplicationContext();
  }  
}

Afterwards, if your want to get your context, simply use:

MyAppContext myContextManager = ((MyAppContext) getApplicationContext());

---- EDIT ----

Once you create your MainActivity, simply call:

myContextManager.setContext(this);

You do this just once. The next times you only need to get it. In your BroadcastReceiver you won't be able to do this, so get it prior to defining it and store it within a variable (for example, called myContextManager), and inside just do something like:

Context context = myContextManager.getContext();



回答2:


step 1:

import android.content.BroadcastReceiver;
import android.content.IntentFilter;

import above your activity.

step 2:

write this in you Activity

    public BroadcastReceiver intentReceiver = new BroadcastReceiver(){
          @Override
           public void onReceive(Context context,Intent intent){
        System.out.println("inside onReceive");

        yourfunction();
    }    
};

step 3: in ocreate() write

    intentfilter = new IntentFilter();
    intentfilter.addAction("SMS_RECEIVED_ACTION");

step 4:

in BroadCastReceiver class include following code

   Intent broadCastIntent = new Intent();
   broadCastIntent.setAction("SMS_RECEIVED_ACTION");
   context.sendBroadcast(broadCastIntent);

hope this will help you..



来源:https://stackoverflow.com/questions/21785784/how-to-use-context-inside-the-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!