I have a service class called myService and I using interval to running the service
here's the code :
public class myService extends Service {
public Runnable mRunnable = null;
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public myService getServerInstance() {
return myService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
Log.d("Service jalan", "beneran dah");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts)
{
int idsql = cn.getID();
if(String.valueOf(cn.getFlag()).equals("0")){
Log.d("Id", String.valueOf(cn.getID()) + " Flag :" + cn.getFlag());
sending a = new sending(); //communicate to server
a.execute();
}
else
{
Log.d("Data kosong", "atau tidak ada flag = 0");
}
}
mHandler.postDelayed(mRunnable, 30 * 1000);
}
};
mHandler.postDelayed(mRunnable, 30 * 1000);
return super.onStartCommand(intent, flags, startId);
}
}
the issue :
when my service still running on if statement but the interval already loop for 30 sec, my service will be start again,
how can I avoid that?
You can use a flag to check whether service is in progress before restarting it as in
boolean isInProgress = false;
mRunnable = new Runnable() {
#Override
public void run() {
Log.d("Service jalan", "beneran dah");
if(!isInProgress){
isInProgress = true;
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts)
{
int idsql = cn.getID();
if(String.valueOf(cn.getFlag()).equals("0")){
Log.d("Id", String.valueOf(cn.getID()) + " Flag :" + cn.getFlag());
sending a = new sending(); //communicate to server
a.execute();
}
else
{
Log.d("Data kosong", "atau tidak ada flag = 0");
}
}
isInProgress = false;
}
mHandler.postDelayed(mRunnable, 30 * 1000);
}
Related
I am trying to run a timer on the activity's onCreate() method but its not running that way. the timer runs on the click of the button. I tried to call the runButtonClick() method in the onCreate() but its not running. in am passing the value through intent from another activity.
Here is my code:
public class TimerActivity extends AppCompatActivity {
private static final String TAG = TimerActivity.class.getSimpleName();
private TimerService timerService;
private boolean serviceBound;
private Button timerButton;
String GetTime;
private TextView timerTextView;
String replaceString;
// Handler to update the UI every second when the timer is running
private final Handler mUpdateTimeHandler = new UIUpdateHandler(this);
// Message type for the handler
private final static int MSG_UPDATE_TIME = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
Intent in = getIntent();
GetTime = in.getStringExtra("order_name");
replaceString = GetTime.replaceAll(" Minutes","");
timerButton = findViewById(R.id.delivered_to_driver);
timerTextView = findViewById(R.id.timer);
timerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// runButtonClick();
}
});
}
#Override
protected void onStart() {
super.onStart();
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Starting and binding service");
}
Intent i = new Intent(this, TimerService.class);
i.putExtra("order_time",replaceString);
startService(i);
bindService(i, mConnection, 0);
}
#Override
protected void onStop() {
super.onStop();
updateUIStopRun();
if (serviceBound) {
// If a timer is active, foreground the service, otherwise kill the service
if (timerService.isTimerRunning()) {
timerService.foreground();
}
else {
stopService(new Intent(this, TimerService.class));
}
// Unbind the service
unbindService(mConnection);
serviceBound = false;
}
}
public void runButtonClick() {
if (serviceBound && !timerService.isTimerRunning()) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Starting timer");
}
timerService.startTimer();
updateUIStartRun();
}
else if (serviceBound && timerService.isTimerRunning()) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Stopping timer");
}
timerService.stopTimer();
updateUIStopRun();
}
}
/**
* Updates the UI when a run starts
*/
private void updateUIStartRun() {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
//timerButton.setText(R.string.timer_stop_button);
}
/**
* Updates the UI when a run stops
*/
private void updateUIStopRun() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
//timerButton.setText(R.string.timer_start_button);
}
/**
* Updates the timer readout in the UI; the service must be bound
*/
private void updateUITimer() {
if (serviceBound) {
timerTextView.setText(timerService.elapsedTime());
}
}
/**
* Callback for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Service bound");
}
TimerService.RunServiceBinder binder = (TimerService.RunServiceBinder) service;
timerService = binder.getService();
serviceBound = true;
// Ensure the service is not in the foreground when bound
timerService.background();
// Update the UI if the service is already running the timer
if (timerService.isTimerRunning()) {
updateUIStartRun();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Service disconnect");
}
serviceBound = false;
}
};
/**
* When the timer is running, use this handler to update
* the UI every second to show timer progress
*/
static class UIUpdateHandler extends Handler {
private final static int UPDATE_RATE_MS = 1000;
private final WeakReference<TimerActivity> activity;
UIUpdateHandler(TimerActivity activity) {
this.activity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message message) {
if (MSG_UPDATE_TIME == message.what) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "updating time");
}
activity.get().updateUITimer();
sendEmptyMessageDelayed(MSG_UPDATE_TIME, UPDATE_RATE_MS);
}
}
}
/**
* Timer service tracks the start and end time of timer; service can be placed into the
* foreground to prevent it being killed when the activity goes away
*/
public static class TimerService extends Service {
private long totalTimeCountInMilliseconds;
private long timeBlinkInMilliseconds;
private CountDownTimer countDownTimer;
private boolean blink;
int time;
private static final String TAG = TimerService.class.getSimpleName();
String thisTime;
// Start and end times in milliseconds
private String startTime, endTime;
// Is the service tracking time?
private boolean isTimerRunning;
// Foreground notification id
private static final int NOTIFICATION_ID = 1;
// Service binder
private final IBinder serviceBinder = new RunServiceBinder();
public class RunServiceBinder extends Binder {
TimerService getService() {
return TimerService.this;
}
}
#Override
public void onCreate() {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Creating service");
}
startTime = "0";
endTime = "0";
isTimerRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Starting service");
}
thisTime = intent.getStringExtra("order_time");
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Binding service");
}
return serviceBinder;
}
#Override
public void onDestroy() {
super.onDestroy();
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Destroying service");
}
}
/**
* Starts the timer
*/
public void startTimer() {
if (!isTimerRunning) {
if (thisTime != null) {
time = Integer.parseInt(thisTime);
} else
Toast.makeText(TimerService.this, "",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds = 60 * time * 1000;
timeBlinkInMilliseconds = 30 * 1000;
// startTime = System.currentTimeMillis();
isTimerRunning = true;
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
if (blink) {
// mTextField.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
// mTextField.setVisibility(View.INVISIBLE);
}
blink = !blink;
}
String a = String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60);
startTime = a;
isTimerRunning = true;
}
#Override
public void onFinish() {
Toast.makeText(TimerService.this, "Finished", Toast.LENGTH_SHORT).show();
}
}.start();
}
else {
Log.e(TAG, "startTimer request for an already running timer");
}
}
/**
* Stops the timer
*/
public void stopTimer() {
if (isTimerRunning) {
endTime = String.valueOf(System.currentTimeMillis());
isTimerRunning = false;
}
else {
Log.e(TAG, "stopTimer request for a timer that isn't running");
}
}
/**
* #return whether the timer is running
*/
public boolean isTimerRunning() {
return isTimerRunning;
}
/**
* Returns the elapsed time
*
* #return the elapsed time in seconds
*/
public String elapsedTime() {
// If the timer is running, the end time will be zero
return startTime;
}
/*Integer.parseInt(endTime) > Integer.parseInt(startTime) ?
(Integer.parseInt(endTime) - Integer.parseInt(startTime)) / 1000 :
(System.currentTimeMillis() - Integer.parseInt(startTime)) / 1000;*//*
}
/**
* Place the service into the foreground
*/
public void foreground() {
startForeground(NOTIFICATION_ID, createNotification());
}
/**
* Return the service to the background
*/
public void background() {
stopForeground(true);
}
/**
* Creates a notification for placing the service into the foreground
*
* #return a notification for interacting with the service when in the foreground
*/
private Notification createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle("Timer Active")
.setContentText("Tap to return to the timer")
.setSmallIcon(R.mipmap.ic_launcher);
Intent resultIntent = new Intent(this, TimerActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(this, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
return builder.build();
}
}
}
I don't understand what the problem might me..your help will be appreciated.thank you in advance...
You startService() called in onStart() method and serviceBound will true after starting service. so that in oncreate() method if condition in runButtonClick will not execute.
I've looking for my issues but not yet find out.
I've create a service in android, and I want whenever I call the service I can operate CRUD
but I dunno how to do that and the tutorial/reffer is so scrimpy.
Here's my code:
DatabaseHandler.java and Contact.java getting from here
myService.java
public class myService extends Service {
public Runnable mRunnable = null;
public myService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
Log.d("Service jalan", "beneran dah");
mHandler.postDelayed(mRunnable, 30 * 1000);
}
};
mHandler.postDelayed(mRunnable, 30 * 1000);
return super.onStartCommand(intent, flags, startId);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
startService(new Intent(this, myService.class));
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Deleted Contacts
db.deleteAll();
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi"));
db.addContact(new Contact("Srinivas"));
db.addContact(new Contact("Tommy"));
db.addContact(new Contact("Karthik"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
//db.deleteContact(new Contact(1));
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
there's a way I can use code insert ("Ravi"); insert ("Srinivas"); insert ("Tommy"); in my MainActivity?
EDIT
I've edit myService.java class like this :
public class myService extends Service {
public Runnable mRunnable = null;
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public myService getServerInstance() {
return myService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
Log.d("Service jalan", "beneran dah");
mHandler.postDelayed(mRunnable, 30 * 1000);
}
};
mHandler.postDelayed(mRunnable, 30 * 1000);
return super.onStartCommand(intent, flags, startId);
}
protected void insert(final String name){
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.addContact(new Contact(name));
}
}
but I've an error of insert in MainActivity.java when I add code below:
Error : non-static method 'insert(java.lang.string)' cannot be referenced from a static context
myService.insert(this, "Coba lagi ah");
myService.insert(this, "Ini yang kedua");
already find out the error on this site but still cant understand how to fix it
use your method calling in onStartCommand(Intent intent, int flags, int startId) cause every time you call a service it'll call this method.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
insert("flix");
return super.onStartCommand(intent, flags, startId);
}
protected void insert(final String name){
DatabaseHandler db = new DatabaseHandler(this);
db.addContact(new Contact(name));
}
Service stop working when turn on /of Wi-Fi many time, when I start service do counter 1,2,3 etc or any thing then turn on /of Wi-Fi many time the service stops working ,I have BroadcastReceiver class doing start service, no exceptions , error appear , only I sent one message to phone to start service..
This is the code inside BroadcastReceiver:
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Intent recorderIntent = new Intent(context, Start2.class);
context.startService(recorderIntent);
}
This My Start2 Service:
public class Start2 extends Service {
private static final String TAG = Start2.class.getSimpleName();
int mStartMode;
#Override
public void onDestroy() {
Log.d(TAG, "Stop Service onDestroy");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
final Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
int i = 0 ;
#Override
public void run() {
try{
//do your code here
Log.d(TAG, "Start Service Repeat Time.. " + i);
i++;
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed( this, 5000 );
}
}
};
handler.postDelayed(runnable, 1000 );
return null;
}
};
task.execute();
return mStartMode;
}
}
I'm implementing service in Activity . When start the activity at that i want to start My-service class.But not print any thing on log cat. So how can i know whether is My-service is start or not.
Here is my Activity code for calling service
Intent intent = new Intent(AllPosts_Page.this, MyService.class);
startService(intent);
here is my service code
public class MyService extends Service
{
protected SQLiteDatabase db;
public Runnable mRunnable = null;
MyDbHelper myDBHelper;
String imageName;
String str_Authentication_Token,str_LoginUserId,str_UserName, result ;
ArrayList<String> pics = new ArrayList<String>();
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public void onCreate() {
super.onCreate();
Log.e("TAG", "ScreenListenerService---OnCreate ");
myDBHelper = new MyDbHelper(this);
myDBHelper.onOpen(db);
//imgUrlLoader=new ImageUrlLoader(getApplicationContext());
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
str_Authentication_Token = sharedPreferences.getString("strAuthentication_Token", "");
str_LoginUserId = sharedPreferences.getString("strUserId", "");
str_UserName = sharedPreferences.getString("strUserName", "");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final Handler mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run()
{
getDoenLoaddata();
downLoadImages();
mHandler.postDelayed(mRunnable, 10 * 1000);
}
};
mHandler.postDelayed(mRunnable, 10 * 1000);
return super.onStartCommand(intent, flags, startId);
}
public void getDoenLoaddata() {
db = myDBHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from ActivityObjectList", null);
if (cursor.moveToFirst())
{
do {
imageName = cursor.getString(cursor.getColumnIndex("imageaudioPath"));
pics.add(imageName);}
while (cursor.moveToNext());
}
cursor.close();
}
public void downLoadImages()
{
for(int i = 0 ; i> pics.size(); i++)
{
String picsName = pics.get(i);
Log.e("picsName "," = " + picsName);
}
}
}
In my menifest.xml file
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false">
</service>
Check your manifest.xml ,
make sure your manifest.xml contains "<service android:name="xx.xx.MyService"></service>".
i am able to display current time and a counter in my textviews but i want to display uploaded and downloaded bytes in the same instead. below are my codes-
in other words, i want to send bandwidth usage to receiver class instead of sending current time and counter.
broadcast service (this calss sends data to receiver class)
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
#Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 10000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("time", new Date().toLocaleString());
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
Bandwidth Usage Example
public class Main extends Activity {
private Handler mHandler = new Handler();
private long mStartRX = 0;
private long mStartTX = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
}
i have tried this but it just shows the package name in both of the textviews
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
private long mStartRX = 0;
private long mStartTX = 0;
#Override
public void onCreate() {
super.onCreate();
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
// RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
// TX.setText(Long.toString(txBytes));
handler.postDelayed(this, 10000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("rxBytes", toString());
intent.putExtra("txBytes", toString());
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}