MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
//String msg="android:"; public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Log.d(msg, "The onCreate() event"); }
public void startService(View view) {
startService(new Intent(getBaseContext(), Myservice.class));
}
// Method to stop the service public void stopService(View view) {
stopService(new Intent(getBaseContext(), Myservice.class));
}
}
Myservice.java
public class Myservice extends Service {
@Nullable @Override public IBinder onBind(Intent intent) {
return null;
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
Manifest.xml code ( adding service tag components )
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.servicedemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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" />
<activity android:name=".abc"></activity>
</application>
</manifest>
Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/button2"
android:layout_centerVertical="true"
android:onClick="stopService"
android:text="stop service"
tools:layout_editor_absoluteX="96dp"
tools:layout_editor_absoluteY="130dp" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="111dp"
android:layout_marginTop="104dp"
android:onClick="startService"
android:text="start service"
tools:layout_editor_absoluteX="61dp"
tools:layout_editor_absoluteY="293dp" />
</RelativeLayout
No comments:
Post a Comment