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

标签 java android android-intent service

如何使用 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/

相关文章:

java - 任何增加 Rational Clearcase 远程客户端内存设置的方法

java - 是否可以在 Java 中对两个字符串数组使用一个 for 循环?

使用名称值对的 Android Volley 发布请求

android - 如何使用 Intent.ACTION_GET_CONTENT 过滤掉不需要的文件

android - 如何将消息从另一个 Activity 传递到蓝牙 Activity

javascript - 如何在前端 react 中设置后端URL

android - 如何在不与其他 View 冲突的情况下在布局中心对齐 textView?

java - ArrayList<ArrayList<String>> 在清除不同的 ArrayList<String> 时被清除

android - ActivityNotFoundException : No Activity found to handle Intent { act=android.intent.action.VIEW dat=文件:///mnt/sdcard/testdata5.pdf

java - 在 Map 中实现按键或 strip 锁定 - 最佳方法?