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

Arm*_*mpc 2 java service android android-intent

如何通过传递context服务putExtra

问题是: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();  
    } 
}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 5

您不能这样做,也不需要这样做。这不仅是Service一个Context,但Service可以调用getApplicationContext()来获取Application对象,如果这是你真正需要的东西。不要传递服务可以单独获得的额外功能。