如何使用上下文中的广播接收器里面呢? [英] how to use context inside the Broadcast Receiver?

查看:486
本文介绍了如何使用上下文中的广播接收器里面呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法创建一个返回一个活动的上下文中的功能,我用广播接收机内部这种情况下,它做什么它应该做的,如果应用程序没有停止,但是当我停止应用程序我不能得到的活动的范围内,因为它返回空值,所以我怎么能保持上下文值由就算我的应用程序就会被杀死广播接收器中使用?

这是返回Context对象的功能和调用构造函数里面的OnCreate()主要活动:

 公共类ContextGen {
静态上下文CONGEN = NULL;公共ContextGen(上下文的背景下){
    CONGEN =背景;}公共静态上下文returnContextGen(){    返回CONGEN;
}

}

和这是广播接收器,其检查接收到的SMS:

 公共类IncomingSms扩展广播接收器{
//获取SmsManager对象
最后SmsManager短信= SmsManager.getDefault();
@覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
        //获取地图从意图扩展数据。
        最后的捆绑包= intent.getExtras();
        //上下文conOfMain = ContextGen.returnContextGen();        如果(捆绑!= NULL){            最终目标[] = pdusObj(对象[])bundle.get(的PDU);            的for(int i = 0; I< pdusObj.length;我++){                SmsMessage currentMessage = SmsMessage
                        ((字节[])pdusObj [I]).createFromPdu;
                字符串phoneNumber的= currentMessage
                        .getDisplayOriginatingAddress();                字符串senderNum = phoneNumber的;
                字符串消息= currentMessage.getDisplayMessageBody();                //我加入到code                Log.i(SmsReceiver,senderNum:+ senderNum
                        +的消息:+消息);                //显示警报
                INT持续时间= Toast.LENGTH_LONG;
                吐司面包= Toast.makeText(背景下,senderNum:
                        + senderNum +,留言:+消息,持续时间);
                toast.show();                如果(message.equalsIgnoreCase(PI锁定)){
                    System.out的
                            .println(锁定entereeeeed =====================);
                    上下文conOfMain = ContextGen.returnContextGen();
                    的System.out.println(上下文是+ conOfMain);
                    LockDevice锁=新LockDevice(conOfMain);
                    lock.lockDeviceNow();
                    abortBroadcast();    }}}}}


解决方案

而不是由你的硬盘的方式做的,只需要使用延长你的应用一个Singleton 。事情是这样的:

 进口android.app.Application;
进口android.content.Context;公共类MyAppContext扩展应用{
  私人上下文的背景下;  公共语境的getContext(){返回语境; }  公共无效setContext(上下文context_){背景= context_; }  公共无效的onCreate(){
    super.onCreate();
    this.context = getApplicationContext();
  }
}

之后,如果你想获得你的情况下,只需使用:

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

---- ----编辑

在您创建MainActivity,只需拨打:

  myContextManager.setContext(本);

您做一次。接下来的时间,你只需要得到它。在你的广播接收器,你将不能够做到这一点,所以变量中之前得到它的定义它并将其存储(例如,名为 myContextManager ),以及里面只是做这样的事情:

 上下文的背景下= myContextManager.getContext();

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

    }}}}}

解决方案

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

这篇关于如何使用上下文中的广播接收器里面呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆