I am trying to access a editText and a Button in a Service. I've seen this answer and this answer, and tried to merge and work out, but no gain. What am I missing here? I have seen other similar answers too and been trying to get it done from last 2 days but all in vain. Any other way of accomplishing it will also be welcome.
Here is the relevant code:
MainActivity.java
btn_start.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View view) {
startService(new Intent(getApplicationContext(), MyService.class));
}
});
MyService.java
Context context = MyService.this;
Activity activity = (Activity) context;
Button stopButton = activity.findViewById(R.id.btn_stop);
EditText editTextUsername = activity.findViewById(R.id.edit_name);
AndroidManifest.xml
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
But I get this error: LOGCAT
11-14 02:55:07.835 5906-5906/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.nwagh.myapplication, PID: 5906 java.lang.RuntimeException: Unable to start service com.example.nwagh.myapplication.MyService@32189af with Intent { cmp=com.example.nwagh.myapplication/.MyService }: java.lang.ClassCastException: com.example.nwagh.myapplication.MyService cannot be cast to android.app.Activity at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3060) at android.app.ActivityThread.access$2300(ActivityThread.java:153) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:5527) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) Caused by: java.lang.ClassCastException: com.example.nwagh.myapplication.MyService cannot be cast to android.app.Activity at com.example.nwagh.myapplication.MyService.onStartCommand(MyService.java:68) at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3043) at android.app.ActivityThread.access$2300(ActivityThread.java:153) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:5527) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) 11-14 02:55:07.844 5906-5906/? E/MQSEventManagerDelegate: failed to get MQSService.
Here is the complete code if you need any more reference.