如何使用 putExtra
将 context
传递给服务?
问题是: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/