I'm trying to create a service in my android project.but the service seems not starting at all.
package serviceexample.javatechig.com.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class HelloService extends Service {
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
}
}
manifest.xml:
<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/>
and main activity:
package serviceexample.javatechig.com.serviceexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, HelloService.class);
startService(intent);
}
});
findViewById(R.id.stop_Service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, HelloService.class);
stopService(intent);
}
});
}
}
no errors but when I press the buttons the service won't get started.onCreate and onStartCommand events not raising.
The package your Service is in:
package serviceexample.javatechig.com.serviceexample;
The class name you use in the Manifest:
<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/>
Those should be same in order for Service to work.
You are using the wrong package name in the AndroidManifest.xml
Replace:
serviceexample.javatechig.HelloService
with
serviceexample.javatechig.com.serviceexample.HelloService
Basically the path name should be same for service activities and all
I finaly found the problem. the service tag in manifest.xml wasn't a child of application tag.If I showed the whole manifest.xml you would find the problem in a minute :)
Related
i am trying to initiate a service from a tab, i have created the buttons in onCreateView method but i startService method doesn't seem to appear anywhere
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Button startServiceButton = (Button) view.findViewById(R.id.strtserviceBtn);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),MyService.class);
startService(intent);
}
});
return view;
}
The startService just tries to create another method of this name.
My Service class is as follows:.
package com.example.a786computer1.mytryfyp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
And i have created the service in my manifest as well, Pls help me regarding this!!
In Fragment you need to call getActivity().startService();.
So replace,
Intent intent = new Intent(getActivity(),MyService.class);
startService(intent);
with
Intent intent = new Intent(getActivity(),MyService.class);
getActivity().startService(intent);
I am studying services, and I have written a code to bind a service by clicking on a button, run a method of the service by clicking on another button and unbinding service by clicking on a third button.
If I try to run the method of the service before binding. I get, obviously, an error message, while if I first bind the service the method is normally called.
The question is, If I click on the third button to unbind the service, despite the service native method on Unbind(Intent intent) gives me a positive feedback, I'm still able to call the service method from the main activity like if it should still be bound.
Here is the Service code
package com.antonello.tavolaccio4;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
/**
* Created by Antonello on 14/05/2017.
*/
public class Servizio extends Service{
public IBinder binder=new MyBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public boolean onUnbind(Intent intent){
System.out.println("unbinded");
return false;
}
public class MyBinder extends Binder{
Servizio getService(){
return Servizio.this;
}
}
public void metodo(){
System.out.println("Metodo del service");
}
}
and here is the Main Activity code:
package com.antonello.tavolaccio4;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
ServiceConnection serviceConnection;
Servizio servizio;
Button button;
Button button2;
Button button3;
boolean bound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Servizio.class);
bindService(intent,serviceConnection, Service.BIND_AUTO_CREATE);
}
});
button2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
servizio.metodo();
}
});
button3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Servizio.class);
unbindService(serviceConnection);
}
});
serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servizio.MyBinder binder=(Servizio.MyBinder)service;
servizio=binder.getService();
bound=true;
System.out.println(bound);
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
}
Is there anything wrong in my unbindService method?
Thank you for any help.
Is there anything wrong in my unbindService method?
You do not have an unbindService() method. You are calling the one that you are inheriting from Context.
It is your job, as part of calling unbindService(), to also set to null any fields tied to the bound connection (in your case, servizio). As it stands, you are leaking memory, and any inherited methods that your service tries calling may throw exceptions because the service is destroyed.
I like to exit my application immediately after starting a service.
The code below causes the activity to finish before the service is started.
How do I set a listener to prompt me when the service is started?
btn = (ImageButton) findViewById(R.id.button );
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(MainActivity.this, MyService.class));
//I want to exit the activity here.
finish(); // this exits the activity before the service is started
}
});
The following are the codes I used, based on the proposal by #Er.Arjunsaini
on the ACTIVITY file, I register to listen for an "Exit App" broadcast.
private final BroadcastReceiver exitAppReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//activity exits when "exit app" broadcast received.
finish();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//REGISTER TO LISTEN FOR THE BROADCAST
LocalBroadcastManager.getInstance(this).
registerReceiver(exitAppReceiver, new IntentFilter(getString(R.string.exit_app)));
btn = (ImageButton) findViewById(R.id.my_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService( new Intent(this, MyService.class));
}
});
}
#Override
public void onDestroy() {
//UNREGISTER THE RECEIVER
LocalBroadcastManager.getInstance(this).
unregisterReceiver(exitFloatingWindowReceiver);
super.onDestroy();
}
on the SERVICE file, I send an "Exit APP" broadcast.
#Override
public void onCreate() {
super.onCreate();
//... do the rest of the Service initializing
//CLOSE ACTIVITY
LocalBroadcastManager.getInstance(this).
sendBroadcast(new Intent(getString(R.string.exit_app)));
}
check out ServiceConnection, onServiceConnected may be method you are looking for to call finish()
HERE you have example
If you use bindService() instead of startService(), you can use the Message based communication system between Activity and Service.
This is explained in this reference.
At the end of the section there's a link to sample classes:
-MessengerService.java
-MessengerServiceActivities.java
Here an example of an Activity with 2 button, one for starting the Service and one for sending a message to the Service that will resend a message to the Activity to close it.
MainActivity.java
package com.pasquapp.brodcasttest01;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public final static int WHAT_CLOSE_ACTIVITY=1;
private Button startServiceButton;
private Button closeButton;
private Messenger activityMessenger;
private Messenger serviceMessenger;
private MyServiceConnection serviceConnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activityMessenger =new Messenger(new ActivityHandler());
initView();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(serviceConnection!=null)
unbindService(serviceConnection);
}
private void initView(){
startServiceButton=findViewById(R.id.button_start_service);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService();
}
});
closeButton=findViewById(R.id.button_close);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(serviceMessenger!=null){
Message msg=Message.obtain();
msg.replyTo=activityMessenger;
msg.what=MyService.WHAT_CLOSE_ACTIVITY;
try {
serviceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
});
}
private class MyServiceConnection implements ServiceConnection{
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
serviceMessenger=new Messenger(iBinder);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
serviceMessenger=null;
}
}
private void startService(){
serviceConnection=new MyServiceConnection();
bindService(new Intent(this,MyService.class),serviceConnection,BIND_AUTO_CREATE);
}
private class ActivityHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
MainActivity.this.finish();
break;
default:
super.handleMessage(msg);
}
}
}}
MyService.java
package com.pasquapp.brodcasttest01;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import androidx.annotation.NonNull;
public class MyService extends Service {
public static final int WHAT_CLOSE_ACTIVITY=1;
private Messenger mMessenger;
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
mMessenger=new Messenger(new ServiceHandler());
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private class ServiceHandler extends Handler{
#Override
public void handleMessage(#NonNull Message msg) {
int what=msg.what;
switch (what){
case WHAT_CLOSE_ACTIVITY:
Messenger messenger=msg.replyTo;
Message closeMsg=Message.obtain();
closeMsg.what=MainActivity.WHAT_CLOSE_ACTIVITY;
try {
messenger.send(closeMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
}
I made a service that every 5 second he put on the screen a TAG (I think this is the name of this). When I make a boot it needs to put the TAG on the screen but he says that the app crashed. Why?
The code:
Android Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="com.YuvalFatal.MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name="com.YuvalFatal.MyService"/>
BroadcastReceiver:
package com.YuvalFatal.ineedhelp;
import java.util.Timer;
import java.util.TimerTask;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastreceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context arg0, Intent arg1) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Intent startServiceIntent = new Intent(arg0, MyService.class);
arg0.startService(startServiceIntent);
}
}, 0, 5000);
}
}
IntentService:
package com.YuvalFatal.ineedhelp;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyService extends IntentService {
private static final String TAG = "com.YuvalFatal.ineedhelp";
public MyService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "Intent Service started");
}
}
I think (yep, I am magician and have great intuition :) your Service constructor should be default:
public class MyService extends IntentService {
...
public MyService() { // Default constructor! Without params!
super("MyService"); // Or another string
}
...
}
Other code looks normal
I am writing a simple service application, below is the code of Activity and Service..,when I am calling startService(), and stopService() its working fine for the one time,in my case it has to give notification..from next time onwards if call again startService(), and stopService() its not giving desired results...
---------- this is my activity class -------------
package com.mypack.serviceex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class serviceex extends Activity implements Button.OnClickListener{
/** Called when the activity is first created. */
Button bt1,bt2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt1 = (Button) findViewById(R.id.Button01);
bt2 = (Button) findViewById(R.id.Button02);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if( v == bt1)
{
Intent i = new Intent(serviceex.this,myservice.class);
Log.i("err","onClick(View v....");
startService(i);
}
else if(v == bt2)
{
Intent i = new Intent(serviceex.this,myservice.class);
Log.i("err","else if(v == bt2)........");
stopService(i);
}
}
}
--------- this is my service -------------
package com.mypack.serviceex;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class myservice extends Service
{
private NotificationManager nmgr;
public void onCreate()
{
super.onCreate();
nmgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Log.i("err","onCreate..........");
Thread th = new Thread(null,new incls(),"service...");
}
public void onStart(Intent intent,int sid)
{
super.onStart(intent, sid);
Log.i("err","onStart........");
}
public void onDestroy()
{
super.onDestroy();
Log.i("err","onDestroy..........");
displayMessage("Stopping Service");
}
public void displayMessage(String str)
{
Log.i("err.","displayMessage.....");
Notification nf = new Notification(R.drawable.icon,str,System.currentTimeMillis());
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,myservice.class), 0);
nf.setLatestEventInfo(this, "Service...", str, pi);
nmgr.notify(R.string.uid, nf);
}
private class incls implements Runnable
{
public void run()
{
Log.i("err","public void run()..........");
System.out.println("In Runnn");
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
None of your methods are #Overrideing the class methods. You have to annote them with #Override. Also, on 2.1 you should use onStartCommand() instead of onStart(). And also note that calling startService() multiple times will only call onCreate() once