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);
Related
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 :)
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 want perform some check continuously. I have defined AsyncTask as
follows,
new AsyncTask<String, Void, String>() {
#Override
protected void onPreExecute() {
Log.d(TAG, "onPreExecute()");
}
#Override
protected String doInBackground(String... params) {
sendData(array);
return null;
}
#Override
protected void onPostExecute(String res) { }
}.execute(userResponse);
But when I terminate the application then thread stops execution.
Service class demo :-
package com.example.My Application;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
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();
}
}
Activity :-
package com.example.My Application;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Method to start the service
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));
}
}
Manifest :-
Add <service android:name=".MyService" />
I am having a problem with setting the onStart method in my app. It always has a strikethrough, saying "This method was deprecated in API level 5. I need onStart, not onStartCommand.
How can I resolve this?
MyNotificationService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyNotificationService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "OnCreate()", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "OnDestroy()", Toast.LENGTH_SHORT).show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
}
Reminder_2.java
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.ImageButton;
public class Reminder_2 extends Activity {
String message;
DatePicker datepicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_2);
datepicker=(DatePicker)findViewById(R.id.datePicker1);
Home();
Next();
Save();
}
private void Next() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton1);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
finish();
}
};
Button.setOnClickListener(myListener);
}
private void Save() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton3);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MyNotificationService.class);
startService(intent);
}
};
Button.setOnClickListener(myListener);
}
private void Home() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton2);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
};
Button.setOnClickListener(myListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reminder, menu);
return true;
}
}
Use onStartCommand().
It you want to know more about how they change it, refer to google documentation like below.
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
#Override
public void onStart(Intent intent, int startId) {
handleStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent, startId);
return START_NOT_STICKY;
}
You can use like this with onStartCommand().
package htin.linnzaw.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
private MediaPlayer mediaplayer;
public MyService()
{
}
#Override
public IBinder onBind(Intent intent)
{
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate()
{
Toast.makeText(this, "Service created", Toast.LENGTH_SHORT).show();
mediaplayer = MediaPlayer.create(this, R.raw.eventually);
mediaplayer.setLooping(false);
}
#Override
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
mediaplayer.start();
return startid;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
mediaplayer.stop();
}
}
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