小白一枚,最近在学习郭神的第一行代码,关于启动service学习中遇到个问题,代码也反复对照了好几遍确认无误,字有点多希望大神们百忙之中多多鞭策指导,感谢!Orz
开发环境:Android studio
运行环境:API21的系统
问题内容:
1 Service启动不了的原因是否是startService()方法处或者是Manifest中的设置问题导致?该如何进行下一步调试?
在学习到第九章启动和停止一个服务按照书中内容照搬,并按书中在创建的MyService类中的各个函数方法中都加上Log输出,运行程序后,点击启动Service的按钮之后,发现Service并没有启动(在应用程序管理运行中没有对应程序服务,Logcat下观察没有对应的Log输出),也没有报异常和错误,debug看了下在点击按钮事件中,startService()语句是执行了的,想知道下一步如何进行调试。
2在回调函数中设置断点是否有用,是否可以像普通函数一样能在debug时停到回调函数中设置的断点处?
这个问题就是上面调试的过程中一直没能将调试过程走到回调函数的断点处,我分析不出来是在回调函数中设置断点就不起作用还是由于自己程序错误根本没有执行到回调函数的原因导致的,所以求指教!
**附上代码如下:**
MainActivity.class
public class MainActivity extends Activity implements OnClickListener {
private Button startService;
private Button stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start_service);
stopService = (Button)findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Log.d("MyService", "From Activity beefore startService executed");
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
Log.d("MyService", "From Activity after startService executed");
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
default:
break;
}
}
}
MyService.class
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent){
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "onCreate executed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand exetuted");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d("MyService", "onDestroy");
super.onDestroy();
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicetest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<Service android:name=".MyService">
</Service>
</application>
</manifest>
调试过程中Logcat输出结果图: