如何通过服务显示Toast - Android

时间:2015-08-05 22:06:41

标签: android service broadcastreceiver toast

所以我在我的应用程序中注册了一个BroadcastReceiver,一旦触发就会启动一个服务。

Service类方法在调用Toast时显示Toast,在测试确实显示之后。

但是如果应用未运行/被销毁,如果传递到Toast.makeText(Context context, CharSequence text, int duration)的上下文是从未实例化的上下文,那么如何显示Toast?

我的意思是,应用程序未运行/被销毁,因此上下文变量从未初始化。

主要活动:

public class MapsActivity extends FragmentActivity {

    MyBroadcastReceiver mBroadcastReceiver = new MyBroadcastReceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Some code here.

        // Instantiate the context.
        context = MapsActivity.this;

        registerReceiver(mBroadcastReceiver, new IntentFilter());

    }
}

BroadcastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            MapsActivity.context.startService(new Intent(context, MyService.class));
        }
    }
}

服务

public class MyService extends Service {

    @Override
    public void onCreate() {
        Toast.makeText(MapsActivity.context, "Service onCreate", Toast.LENGTH_LONG).show();
    }

    // Some other super methods.
}

1 个答案:

答案 0 :(得分:1)

这是有效的,因为您的Context保存在一个静态字段中,该字段的生命周期与该过程之一一样长。正在运行的服务使进程保持活动状态。

然而,这是糟糕的设计!您不应该以这种方式对上下文进行引用,特别是如果您不需要:

Service本身会实现Context,因此您可以将MapsActivity.context替换为this。当然,同样适用于BroadcastReceiver:使用参数context代替MapsActivity.context