首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法bindService Android()

无法bindService Android()
EN

Stack Overflow用户
提问于 2016-11-24 11:09:22
回答 1查看 397关注 0票数 0

我已经关注这个问题很长一段时间了,但是我不能修复在试图访问空对象上的ResolveInfo.serviceInfo时抛出的空指针异常。(从API 20开始启动服务时必须明确意图)

下面是.aidl接口:

代码语言:javascript
复制
package com.example.playerclient;

interface AIDLinterface {
    void Play_Clip(int id);
    void Pause_Playback();
    void Resume_Playback();
    void Stop_Player();
}

下面是相关的客户端代码(onResume()是抛出NPE的地方)

代码语言:javascript
复制
public class PlayerClientMain extends AppCompatActivity
{

    Button button;
    private AIDLinterface mAIDLinterface;
    private boolean mIsBound = false;

    private ServiceConnection mServiceConn = new ServiceConnection()
    {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iservice)
        {
            Log.v("SERVICE CONNECTED", "SERVICE CONNECTED");
            mAIDLinterface = AIDLinterface.Stub.asInterface(iservice);

            Toast.makeText(getApplicationContext(), "service connected", Toast.LENGTH_SHORT).show();

            mIsBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName)
        {
            Log.v("SERVICE DISCONNECTED", "SERVICE DISCONNECTED");
            mAIDLinterface = null;
            Toast.makeText(getApplicationContext(), "service disconnected", Toast.LENGTH_SHORT).show();
            mIsBound = false;

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_client_main);
        button = (Button) findViewById(R.id.button);
    }


    @Override
    protected void onResume()
    {
        super.onResume();

        if (!mIsBound)
        {
            boolean b = false;
            Intent i = new Intent(AIDLinterface.class.getName());

            ResolveInfo info = getPackageManager().resolveService(i, Context.BIND_AUTO_CREATE); //this is always null
            i.setComponent(new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name)); //NPE because info is null

            b = bindService(i, this.mServiceConn, Context.BIND_AUTO_CREATE);

            if (b)
                Log.i("SUCCESS:", "bindService() success!");
            else
                Log.i("FAILURE:", "bindService() failed!");
        }
    }
}

服务代码无关紧要,因为我无论如何都无法到达bindService()行。有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2016-11-24 11:35:55

我认为问题在于创建意图本身。

假设AIDLinterface.class是一个服务类,您应该像这样创建意图:

代码语言:javascript
复制
Intent i = new Intent(this, AIDLinterface.class);

有关详情,请参阅https://developer.android.com/guide/components/services.html

干杯~

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40777470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档