如何使用BroadCastReceiver获取AppcationContext

时间:2015-07-04 06:53:35

标签: android broadcastreceiver alarmmanager

此问题与How to use getApplicationContext in BroadcastReceiver class?类似。

但我不知道他之前的活动是怎么回事。所以我不知道如何解决我的问题。

这是我的活动:

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

完整的代码,我从这里得到它:http://javatechig.com/android/repeat-alarm-example-in-android

这是我的AlarmReceiver.class扩展BroadCastReceiver实现了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);
    }
}

任何人都可以帮助我?

1 个答案:

答案 0 :(得分:0)

你在onReceive方法

initIndoorAtlas(context);

和方法

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

如果方法是表单实现接口,那么使用此代码..

private Context context:

和onReceive方法

this.context = context;

在你的方法中使用上下文,因为它是全局变量,我们可以访问它。