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
Related
I am using this library for download
it works well but i want download my file in background i don't want use AsyncTask because it has so much code and my project is long .
so help me to download in background with this lib
this is my code :
Ion.with(getApplicationContext())
.load("http://example.com/pdf.zip") // file address
.progress(new ProgressCallback() {
#Override
public void onProgress(long downloaded, long total) {
progressBar.setProgress((int) downloaded);
progressBar.setMax((int) total);
}
})
.write(new File(direct + File.separator + "signal.zip")) //saving location
.setCallback(new FutureCallback<File>() {
#Override
public void onCompleted(Exception e, File result) {
btn24.setText("show");
btn24.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Card.this, Show.class);
startActivity(intent);
}
});
}
});
and this is my activity code :
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.bumptech.glide.Glide;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.ProgressCallback;
import org.zeroturnaround.zip.ZipUtil;
import java.io.File;
import java.net.URL;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class Card extends AppCompatActivity {
private Button btn1;
private ProgressBar progresBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
//getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//toolbar.setNavigationIcon(R.drawable.toolbar_back_ltr);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
progressBar = (ProgressBar) findViewById(R.id.bar);
btn1 = (Button) findViewById(R.id.button);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(Card.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(Card.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Card.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
} else {
//do something
}
} else {
//do something
}
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
direct = new File(Environment.getExternalStorageDirectory() + "/S/A");
if (!direct.exists()) {
direct.mkdirs();
}
btn1.setText("Downloading . . .");
Ion.with(getApplicationContext())
.load("http://example.com/pdf.zip") // file address
.progress(new ProgressCallback() {
#Override
public void onProgress(long downloaded, long total) {
progressBar.setProgress((int) downloaded);
progressBar.setMax((int) total);
}
})
.write(new File(direct + File.separator + "AmarVAEhtemal.zip")) // saving location
.setCallback(new FutureCallback<File>() {
#Override
public void onCompleted(Exception e, File result) {
btn1.setText("show");
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Card.this, Show.class);
startActivity(intent);
}
});
}
});
}
});
}
}
Use foreground service to protect your progress being killed.
use startService to start service
use startForeground(NOTIFICATION_ID, notification); to prevent from desctroying.
use your lib.
PROFIT!
start service:
Intent intent = new Intent(this, HelloService.class);
startService(intent);
service class:
public class ExampleService extends Service {
#Override
public void onCreate() {
// The service is being created
showForegroundNotification("some service");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
#Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
#Override
#Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
private static final int NOTIFICATION_ID = 1;
private void showForegroundNotification(String contentText) {
// Create intent that will bring our app to the front, as if it was tapped in the app
// launcher
Intent showTaskIntent = new Intent(getApplicationContext(), MyMainActivity.class);
showTaskIntent.setAction(Intent.ACTION_MAIN);
showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
showTaskIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle(getString(R.string.app_name))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_notification)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.build();
startForeground(NOTIFICATION_ID, notification);
}
}
start foreground example
https://gist.github.com/kristopherjohnson/6211176
androidManifest.xml
<service android:name=".ExampleService" . . . >
</service>
put pass extrad data use with:
Intent intent = new Intent(this, HelloService.class);
intent.putExtra("MYPARAMNAME","MYURL");
startService(intent);
to retrieve use this:
onStartCommand(Intent intent, ...
Bundle extras = intent.getExtras();
filename = extras.getString("MYPARAMNAME");
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'm supposed to add a timer to my service class that prints a message to LogCat every 10 seconds. Nothing in the service class is printing once I call the startService method and I have no idea why.. Any ideas?
package com.murach.reminder;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ReminderActivity extends Activity implements OnClickListener {
private Button startServiceButton;
private Button stopServiceButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
startServiceButton = (Button) findViewById(R.id.startServiceButton);
stopServiceButton = (Button) findViewById(R.id.stopServiceButton);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent(this, ReminderService.class);
switch (v.getId()) {
case R.id.startServiceButton:
// put code to start service and display toast here
startService(serviceIntent);
Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show();
break;
case R.id.stopServiceButton:
// put code to stop service and display toast here
stopService(serviceIntent);
Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
break;
}
}
}
package com.murach.reminder;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class ReminderService extends Service
{
private Timer timer;
public void onCreate()
{
Log.d("Reminder", "Service created");
startTimer();
}
#Override
public IBinder onBind(Intent intent)
{
Log.d("Reminder", "No binding for this activity");
return null;
}
public void onDestroy()
{
Log.d("Reminder", "Service destroyed");
stopTimer();
}
private void startTimer() {
TimerTask task = new TimerTask() {
public void run() {
Log.d("Reminder", "Timer task executed");
}
};
timer = new Timer(true);
int delay = 1000 * 10;
int interval = 1000 * 10;
timer.schedule(task, delay, interval);
}
private void stopTimer()
{
if (timer != null)
{
timer.cancel();
}
}
}
And here is how I register the service in the Manifest (in a service element, it wouldn't let me type it out completely)
android:name="com.murach.reminder.ReminderService"
The package names do not match. There is a spelling mistake in the word murach in your Manifest declaration.
I have two activities and one service all in one app
activity2 will start and stop the service
activity1 is the main UI
the service have two supposed tasks:
1- receive data from a server though a socket and pass it to activity1 to update the user interface
2- receive data from activity1 and send it to the sever
the problem is i wasn't able to have a clear idea about how i can make the service exchange data with the activity
i read about AIDL , Binding here http://developer.android.com/guide/components/bound-services.html
i couldn't apply it on my codes, even after three weeks of hard work i didn't get it !!!
thank you !
service:
public class NetService extends Service {
public static Client client = new Client("192.168.1.5");
Thread call;
BufferedWriter out;
int a;
String a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15;
public static int get = 5;
Intent intent2;
NotificationManager mNM;
private final IBinder mBinder = new LocalBinder();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
NetService getService() {
return NetService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
a1 ="Hello everyone !!"
new Thread(new Runnable(){
public void run() {
try {
client.connectToServer();
} catch (IOException e) {
e.printStackTrace();
}
try {
client.setstream();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
while(true){
try {
client.getFromServer();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
client.sendToServer();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
client.closeall();
super.onDestroy();
}
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = ("remote_service_started");
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.togon, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Connect.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, ("remote_service_label"),
text, contentIntent);
// Send the notification.
// We use a string id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.remote_service_started, notification);
}}
UI activity :
package com.bannob.shms;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.bannob.shms.NetService.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.VideoView;
import android.widget.ViewFlipper;
public class Main extends Activity {
public static ViewFlipper vf, lightvf, secvf;
private Float oldTouchValue;
public static TextView tv1, lighttv, sectv, tvlight1, tvlight2, tvlight3,
tvlight4, gasactivetv, flameactivetv, mdetect1tv, automodtv, indoortv, hmdtv;
public static LinearLayout wallpaper, fansbanner;
public static ToggleButton envtog1, envtog2, envtog3, envtog4;
public static Switch lights1, lights2, lights3, lights4;
public static VideoView vview;
public static ImageView safeiv1, safeiv2, seciv1, seciv2, secbubble, safebubble;
Typeface tf;
BufferedReader in = null;
File file;
File values;
String[] valuesArray= new String[30];
int a;
String a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20;
NetService mService;
boolean mBound = false;
/**********************************************************************/
/* Look for the definitions of the previous declarations below !!!! */
/**********************************************************************/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // reference to activity_main.Xml at layout Folder
TextView tv1 = (TextView) findViewById ()
onStart();
tv1.setText(mService.a1);
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, NetService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
second activity (which start the service):
package com.bannob.shms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Connect extends Activity {
EditText conet1;
Button con ;
public static Boolean state = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
con = (Button) findViewById(R.id.conb1);
conet1 = (EditText) findViewById(R.id.conet1);
con.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(state == false ){
startService(new Intent(getBaseContext(), NetService.class));
state = true;
con.setText("Disconnect");
}
else{
stopService(new Intent(getBaseContext(), NetService.class));
state = false;
con.setText("Connect");
}
}
});
}
}
Recommended way
BroadCastReceiver & sendBroadcast
in you activities register a BroadcastReciver
IntentFilter newFileReceiverfilter = new IntentFilter(App.INTENT_NEW_FILE_COMMING ) ;
registerReceiver(newfileReceiver, newFileReceiverfilter);
newfileReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent in) {
Log.i("FileName", in.getStringExtra(IntentExtrasKeys.NF_FILE_NAME) + "");
}
}
in you Service broadCast an Intent with the data you want to send as Extra
Intent intent = new Intent(App.INTENT_NEW_FILE_COMMING);
intent.putExtra(IntentExtrasKeys.NF_FILE_NAME, "img2.jpg" ) ;
ctx.sendBroadcast(intent);
to send more data to the service from the activities just send more Intents
there is dirty way u can let the service write it vaule in static class and read the static class from the activities
I'm trying to create a service which will start by the user request in the application.
After the user will choose an update interval, the service will run in the operation system background, and will send a non-relevant message.
I've tried to write the service according to the example for Service class API.
For some reason, I figured in debug (when running doBindService() method) that mUpdateBoundService is getting null.
My second question is whether I can use "Toast" inform message outside an application ? (As kind of a desktop notification).
Can anyone help ? Here is my short code:
UpdateService.java
package android.update;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class UpdateService extends Service {
private NotificationManager mNM;
private final IBinder mBinder = new UpdateBinder();
private int updateInterval;
public class UpdateBinder extends Binder {
UpdateService getService() {
return UpdateService.this;
}
}
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, updateInterval);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
class UpdateTimeTask extends TimerTask {
public void run() {
showNotification();
}
}
public void showNotification() {
Toast.makeText(this, "Hi", 10);
}
#Override
public IBinder onBind(Intent intent) {
updateInterval = intent.getExtras().getInt(getString(R.string.keyUpdateInterval));
return mBinder;
}
}
UpdateActivity.java
package android.update;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateActivity extends Activity {
private UpdateService mUpdateBoundService;
private boolean mIsBound = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClickStartUpdateService(View view) {
switch (view.getId()) {
case R.id.btnStartUpdateService:
doBindService();
//Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
mUpdateBoundService.showNotification();
break;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mUpdateBoundService = ((UpdateService.UpdateBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mUpdateBoundService = null;
}
};
private void doBindService() {
Intent updateActivityIntent = new Intent(UpdateActivity.this,
UpdateService.class);
EditText txtUpdateInterval = (EditText) findViewById(R.id.txtUpdateInterval);
int interval = Integer.parseInt(txtUpdateInterval.getText().toString());
updateActivityIntent.putExtra(getString(R.string.keyUpdateInterval), interval);
bindService(updateActivityIntent, mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
}
Your toast is not showing because you are not telling it to. Try:
public void showNotification() {
Toast.makeText(this, "Hi", 10).show();
}
For your service issue, I think that you do not properly understand how services & activities work together. A service can run independently of a service, or you can have a service whose lifecycle matches that of a given activity. From your code, it is not clear which of these models you are following. Your implementation will cause the service to wake periodically, but only while your activity is running. If the user switches to another activity, your service will no longer be woken.
If you want a service to wake periodically independently of the activity, then you need to run your timer event in the service itself. Better still use an Alarm to wake your service: Register an Alarm with AlarmManager which will fire an Intent at a future point (or regular intervals, if you prefer), and extend your service from IntentService, override onHandleIntent() and add the necessary Intent Filter to your Service entry in the manifest.