Android在服务service里使用Toast显示

参考网址:https://blog.csdn.net/cqx13763055264/article/details/79179731

 

在Service中使用Toast

private Handler handlerToast = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    Toast.makeText(getApplicationContext(), "显示的内容!",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

注意:getApplicationContext()使用Toast时要使用全局的Context,如果在Activity中有公共方法可供使用,写法如下

public void showToast(String text){
   Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}

这样是显示不出来的,必须使用的是全局的Context

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Service 在后台生成随机数。以下是一份示例代码: ```java public class RandomNumberService extends Service { private static final String TAG = "RandomNumberService"; private final IBinder mBinder = new LocalBinder(); private final Random mGenerator = new Random(); @Override public void onCreate() { Log.d(TAG, "onCreate"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand"); return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { Log.d(TAG, "onBind"); return mBinder; } public class LocalBinder extends Binder { RandomNumberService getService() { return RandomNumberService.this; } } public int getRandomNumber() { return mGenerator.nextInt(); } } ``` 然后在你的 Activity ,通过启动 Service 和绑定 Service 的方式获取随机数: ```java public class MainActivity extends AppCompatActivity { private boolean mBound = false; private RandomNumberService mService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, RandomNumberService.class); startService(intent); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); if (mBound) { unbindService(mConnection); mBound = false; } } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { RandomNumberService.LocalBinder binder = (RandomNumberService.LocalBinder) iBinder; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName componentName) { mBound = false; } }; public void onGetRandomNumber(View view) { if (mBound) { int randomNumber = mService.getRandomNumber(); Toast.makeText(this, "Random number: " + randomNumber, Toast.LENGTH_SHORT).show(); } } } ``` 其 `onGetRandomNumber` 是一个按钮的点击事件,当用户点击按钮时,会调用 `getRandomNumber` 方法获取随机数,并通过 Toast 显示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值