2014-02-14 8 views
0

액티비티의 컨텍스트를 반환하는 함수를 생성하고 브로드 캐스트 리시버 내부에서이 컨텍스트를 사용했으며, 애플리케이션이 중지되지 않은 경우 수행해야하는 작업을 수행하지만 애플리케이션을 중지하면 컨텍스트를 가져올 수 없습니다. 액티비티가 null 값을 반환하므로 내 애플리케이션이 죽어도 방송 수신기에서 사용할 컨텍스트 값을 어떻게 유지할 수 있습니까? 브로드 캐스트 수신기에서 컨텍스트를 사용하는 방법?

문맥 객체를 반환하는 함수이고, 생성자는 주 활성 OnCreate() 내부 호출 :

public class ContextGen { 
static Context conGen = null; 

public ContextGen(Context context) { 
    conGen = context; 

} 

public static Context returnContextGen() { 

    return conGen; 
} 

}

이 수신 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(); 

    }}}}} 
+0

이 왜 방송 수신기에서 클래스 컨텍스트를해야합니까? –

+0

은 브로드 캐스트 리시버 내부에서 일부 특정 작업을 수행하기 위해 컨텍스트가 필요한 일부 기능을 호출합니다. –

답변

2

어려운 방법으로 처리하는 대신, Application을 확장하는 싱글 톤을 사용하십시오. 이런 식으로 뭔가 : 당신의 희망이 당신의 컨텍스트를 얻을 경우

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

이후, 단순히 사용

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

---- 편집 ----

생성되면 당신의 MainActivity로 전화하기 만하면됩니다.

myContextManager.setContext(this); 

이 작업은 한 번만 수행됩니다. 다음 번엔 단지 그것을 얻을 필요가 있습니다. 당신에 BroadcastReceiver이 작업을 수행 할 수 없습니다, 그래서 정의하기 전에 그것을 얻을하고 변수 내에 저장 (예를 들어, myContextManager라고도 함), 그냥 같은 것을 할 내부 :

Context context = myContextManager.getContext(); 
+0

답변 해 주셔서 감사합니다.하지만이 질문에 답하고자하는 것은 컨텍스트가 null이 될 수 있기 때문에 내 응용 프로그램이 종료 되더라도 브로드 캐스트 리시버 내부에서이 컨텍스트를 사용하는 방법입니다. 어떻게 유지할 수 있습니까? –

+0

해당 앱이 꺼져있는 상태로 'BroadcastReceiver'를 사용하려는 경우'onReceive (Context context, Intent intent)'메소드에서 제공 한'Context' 만 사용해야합니다 - 다른 종류의' 컨텍스트 '또는 어딘가에 저장하는 것은 나쁜 생각입니다. – nKn

+0

그게 내가 찾고 있었던 덕분이야! –

3

1 단계를 :

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

귀하의 활동을 가져 오십시오.

2 단계 : 당신의

쓰기이 활동

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

     yourfunction(); 
    }  
}; 

3 단계 : ocreate에서()

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

4 단계 쓰기 : 브로드 캐스트 리시버 클래스의

포함 다음 코드

이 당신에게 도움이 될 것입니다
Intent broadCastIntent = new Intent(); 
    broadCastIntent.setAction("SMS_RECEIVED_ACTION"); 
    context.sendBroadcast(broadCastIntent); 

희망 ..

+0

답장을 보내 주셔서 감사합니다. 그러나 이것이 방송 수신기 내부에서 사용하는 상황에 도움이됩니까? 때문에 애플 리케이션이 중지되면 컨텍스트가 null이됩니다. –

+0

예, 그렇습니다 ... –

관련 문제