0

sendBroadcast는 활동 컨텍스트 또는 응용 프로그램 컨텍스트에서 호출 할 수 있습니다.은 활동 컨텍스트를 사용하는 것과 응용 프로그램 컨텍스트를 사용하여 sendBroadcast를 사용하는 것의 차이점은 무엇입니까

문맥이 이미 응용 프로그램 컨텍스트 인 경우 다른 문의 사항이 있습니다. context.getApplicationContext()를 수행하면 그 자체가 올바르게 반환됩니다. 맞습니까?

하나의 시나리오는 나중에이 컨텍스트를 사용하여 다른 서비스를 바인딩하거나 점심을 먹는 수신자 객체에 활동 컨텍스트를 전달할 수 있습니다. 이 리시버는 몇 가지 다른 활동에서 로컬로 인스턴스화됩니다. 차이가 어쩌면 그냥 수신기에 applicationConext 전달되지 수있는 경우 컨텍스트는

이상은 그냥 얻을 수있는,

, 아래와 같이 수신기 내부이라고하여

에 컨텍스트 전달
onReceive(Context context, Intent intent), 

거기에 context.getApplicationContext를 수행 하시겠습니까?

// inside the receiver it will the following with the context: 
mContext.bindService(new Intent(mContext, OtherService.class), mInitServiceConnection, Context.BIND_AUTO_CREATE); 

mContext.unbindService(mInitServiceConnection); 

Intent newStartIntent = new Intent(mContext, InitService.class); 
mContext.startService(newStartIntent); 

수신기과 같다 :

class LocalBroadcastReceiver extends BroadcastReceiver { 

    private final Context mContext; 

    public LocalBroadcastReceiver(@NonNull Context context) { 
     mAppContext = context; 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 

    // could it here use the context to get application context, like: 
      mContext = context.getApplicationContext() 

      //then do something like: 
      Intent newStartIntent = new Intent(mContext, InitService.class); 
      mContext.startService(startMailAccountInitIntent); 
    } 
} 
+0

나는 onReceive 컨텍스트 컨텍스트 context (Activity) user (developer)를받은 후 applicationContext가 아닌 activity 컨텍스트는 해당 컨텍스트를 사용하여 해당 활동을 변경합니다. – phpdroid

+0

감사합니다. phpdroid! onReceive()의이 컨텍스트는 어디에서 왔습니까? 방송은 activity 또는 applicationContext를 통해 전송 될 수 있습니다. – lannyf

답변

0

I onReceive() 작동에서의 ApplicationContext를 얻기 위해 컨텍스트를 사용하여 내 경우,

onReceive(Context context, Intent intent) { 
var appContext = context.applicationContext 

    ... 
mContext.bindService(new Intent(appContext, OtherService.class), mInitServiceConnection, Context.BIND_AUTO_CREATE); 

} 

을 얻을 것이다 문맥을 사용할 수 없습니다
android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to bind to services