绑定本地服务,得到服务对象为空,求解答

蓝天&前行 蓝天&前行 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
服务:

public class MyService extends Service {
private MyBind mBind = new MyBind();

@Override
public IBinder onBind(Intent intent) {

return mBind;
}

public String mCallMethod() {
return "我被调用了";
}

class MyBind extends Binder implements IService {
@Override
public String reciveMessage() {
String str = mCallMethod();
return str;
}
}
}

服务调用者:

public class ServiceDemoActivity extends Activity {

private IService mService;
private Button call;
private TextView dis;
private Button bind;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
call = (Button) findViewById(R.id.caller);
bind=(Button)findViewById(R.id.bind);
bind.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
bindService();

}
});
dis = (TextView) findViewById(R.id.content);
bindService();
call.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String str=mService.reciveMessage();
dis.setText(str);
}
});

}

public void bindService(){
bindService(new Intent(this, MyService.class), new MyConnection(), BIND_AUTO_CREATE);
}

public void unBindService(){
unbindService(new MyConnection());
}

class MyConnection implements ServiceConnection{

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService=(IService)service;
}

@Override
public void onServiceDisconnected(ComponentName name) {

}

}
}

main.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<Button android:id="@+id/bind"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="绑定服务"
/>

<Button android:id="@+id/caller"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="调用服务"
/>


<TextView android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="30dip"
android:text=""
android:gravity="center"
android:layout_marginTop="30dip"
android:layout_gravity="center"
/>

</LinearLayout>

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.service.demo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ServiceDemoActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<Service android:name=".MyService" />

</application>
</manifest>
...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
蓝天&前行
Android 80,490 成员 91,375 内容