Issue
The AVD says "Unfortunately, Service has stopped", where service is the name of my app. Please tell me where I went wrong. I have posted the code of the two files :
MainActivity.java:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start, stop;
start = (Button) findViewById(R.id.Button1);
stop = (Button) findViewById(R.id.Button2);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent(MainActivity.this, MyService.class);
startService(service);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent name = new Intent(MainActivity.this, MyService.class);
stopService(name);
}
});
}
}
MyService.java:
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new AlertDialog.Builder(this).setTitle("Argh").setMessage("Watch out!").setNeutralButton("Close", null).show();
return 0;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:text="Play" />
<Button
android:id="@+id/Button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/Button1"
android:layout_alignBottom="@+id/Button1"
android:layout_centerHorizontal="true"
android:text="Stop" />
</RelativeLayout>
This is what LogCat says:
04-18 18:48:48.724: E/Trace(852): error opening trace file: No such file or directory (2)
04-18 18:48:49.683: D/gralloc_goldfish(852): Emulator without GPU emulation detected.
The error message is displayed after I click on the start button.
Thanks in advance :)
Solution
I don't think you can generate an AlertDialog in a service without any context to the activity. If you just want to know if the service is started or not, try logging it:
Log.i("MyService","Service started");
And check for it in you logcat by doing:
logcat -s "MyService"
If you want to display an AlertDialog, trying to look at this post.
Answered By - wangyif2
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.