gpt4 book ai didi

java - 使用 putExtra 将上下文传递给服务

转载 作者:搜寻专家 更新时间:2023-11-01 07:57:40 25 4
gpt4 key购买 nike

如何使用 putExtracontext 传递给服务?

问题是:android.os.Application 无法转换为 java.io.Serializable

如何解决这个问题?

// main activity
public void btnGetLocate() {
Intent intent = new Intent(this, Sleeper.class);
intent.putExtra("context", (Serializable) getApplicationContext());
startService(intent);
}

// another file
public class MyService extends IntentService {
public Sleeper() {
super("MyService");
}

protected void onHandleIntent(Intent intent) {
Context context = (Context) intent.getExtras().getSerializable("context"); // make Error, main problem
MyClass mc = new MyClass(context);
...
}

public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "destroyed"), Toast.LENGTH_SHORT).show();
}
}

最佳答案

你不能这样做,也不需要这样做。 Service不仅是一个Context,而且Service可以调用getApplicationContext()获取Application object 如果那是你真正需要的。不要传入服务可以自行获取的额外内容。

关于java - 使用 putExtra 将上下文传递给服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25685993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com