gpt4 book ai didi

java - 我的服务没有启动

转载 作者:行者123 更新时间:2023-12-01 15:22:39 26 4
gpt4 key购买 nike

我正在尝试在后台启动服务。当用户选中该复选框时,它应该启动服务并显示 MyService 类中的 Toast。但开始服务后我没有得到那个 toast 。我在下面的代码中做错了什么?

我的主要 Activity

public class SampleServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);

cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if(isChecked) {
Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_LONG).show();
startService(new Intent(getBaseContext(), MyService.class));
} else {
Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_LONG).show();
stopService(new Intent(getBaseContext(), MyService.class));
}
}

});
}
}

我的服务等级

public class MyService extends Service {

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}

//method to stop service
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}

最佳答案

可能您没有在 list 中注册 MyService 服务,因此注册为:

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

<application android:icon="@drawable/xxx" android:label="@string/app_name" >

<activity> ... </activity>

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

</application>
</manifest>

关于java - 我的服务没有启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com