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>".
Related
I am using a service in my application in order to get data from the server and save received data in my local database.
But when I am using the application and my service will run in the background the application works too slow.
This is my service class that I used:
public class InternetService extends Service implements Loader.OnLoadCompleteListener<Cursor> {
public static final int notify = 5 * 60 * 60 * 1000; //interval between two services(Here Service run every 1 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
private ArrayList<FileModel> failedIDDownloads = new ArrayList<>();
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "my_package";
Intent intent;
int counter = 0;
private CursorLoader cursorLoader;
private EncycDatabase encycDB;
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
cursorLoader = new CursorLoader(this, Uri.parse(EncycDatabase.CONTENT_PROVIDER_URL),
null, null, null, null);
cursorLoader.registerListener(1, this);
cursorLoader.startLoading();
mHandler.removeCallbacks(sendUpdatesToUI);
mHandler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the cursor loader
if (cursorLoader != null) {
cursorLoader.unregisterListener(this);
cursorLoader.cancelLoad();
cursorLoader.stopLoading();
}
}
#Override
public void onLoadComplete(Loader<Cursor> loader, Cursor cursor) {
encycDB = new EncycDatabase();
try {
while (cursor.moveToNext()) {
G.TOKEN = (cursor.getString(cursor.getColumnIndex("user_session_token")));
}
populateEncyclopediaData();
Thread searchTagThread = new Thread(new Runnable() {
#Override
public void run() {
populateSearchTagsEncyc();
populateSearchTags();
}
});
G.handler.postDelayed(new Runnable() {
#Override
public void run() {
checkForDownloadFiles();
}
},10 *60* 1000);
searchTagThread.start();
} catch (Exception e) { //When happened an error in getting Token!
e.printStackTrace();
}
}
private void populateEncyclopediaData() {
final APIService service = ServiceGenerator.createService(APIService.class,
new PreferenceManager(G.context).getLastUpdateForEncyclopediaData(), G.TOKEN);
service.getLastChanges()
.subscribeOn(Schedulers.newThread())
.observeOn(Schedulers.io())
.subscribe(new Observer<Response<ArrayList<ServerLastChangesModel>>>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Response<ArrayList<ServerLastChangesModel>> response) {
Log.i("LOGO_Encycloedia", "Request code: " + response.code());
if (response.code() == 200) {
G.encyclopediaArray.clear();
for (int i = 0; i < response.body().size(); i++) {
EncyclopediaModel lcModel = new EncyclopediaModel();
lcModel.setEncyclopedia_id(response.body().get(i).getEncyclopediaId());
lcModel.setEncyclopedia_title(response.body().get(i).getEncyclopediaTitle());
lcModel.setEncyclopedia_modified_date(response.body().get(i).getEncyclopediaModifiedDate());
lcModel.setEncyclopedia_deleted(response.body().get(i).getEncyclopediaDeleted());
lcModel.setEncyclopedia_content_id(response.body().get(i).getEncyclopediaContentId());
lcModel.setEncyclopedia_out_desc_text_id(response.body().get(i).getEncyclopediaOutDescTextId());
lcModel.setEncyclopedia_in_desc_text_id(response.body().get(i).getEncyclopediaInDescTextId());
lcModel.setEncyclopedia_order_in_parent(response.body().get(i).getEncyclopediaOrderInParent());
lcModel.setEncyclopedia_parent_id(response.body().get(i).getEncyclopediaParentId());
lcModel.setEncyclopedia_is_inline_parent(response.body().get(i).getEncyclopediaIsInlineParent());
lcModel.setEncyclopedia_style_sheet(response.body().get(i).getEncyclopediaStyleSheet());
G.encyclopediaArray.add(lcModel);
}
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
try {
encycDB.insertIntoEncyclopediaDB(G.encyclopediaArray);
new PreferenceManager(G.context).writeLastUpdateForEncyclopediaData();
} catch (Exception e) {
e.printStackTrace();
}
populateContentData(encycDB.getContentIdsFromEncyclopedia());
}
});
}
As you can see, I used threads, but it doesn't help!
I can't find out where is the problem.
The Service runs in background but it runs on the Main Thread of the application. And IntentService runs on separate worker thread.
Move your code to IntentService.
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);
}
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));
}
Actually i have a TCP Client that onStart connect to the server and send the device IP and number to it, but now i want that when the application is getting closed ( onDestroy ) delay it for some seconds ( the right time to reopen the connection and send another message ) and send another message in which i'm saying that the device is offline.
I've tryed to do it onDestroy method but probably it's madness and obviously
that didn't worked ( i tryed to do the following stuff onDestroy :
protected void onDestroy() {
new ConnectTask().execute("");
if (client != null) {
client.sendMessage(trm + "OFFLINE");
}
if (client != null) {
client.stopClient();
}
super.onDestroy();
server.onDestroy();
}
Here is my MainActivity code where i evocate the TCP Client and sending start message:
public class MainActivity extends AppCompatActivity {
Server server;
static Client client;
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
static TextView msgServer;
static String ipp;
static String trm;
static DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
msgServer = (TextView) findViewById(R.id.serverMSG);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
startService(new Intent(MainActivity.this,FinalizingOperationsService.class));
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
startConnection.postDelayed(runnableConnection,5000);
startMessage.postDelayed(runnableMessage,5500);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public static class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
msgServer.setTextColor(Color.parseColor("#00FF00"));
msgServer.setText("ONLINE");
Log.d("test", "response " + values[0]);
}
}
static Handler startConnection = new Handler();
static Runnable runnableConnection = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
}
};
static Handler startMessage = new Handler();
static Runnable runnableMessage = new Runnable() {
#Override
public void run() {
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
if (client != null) {
client.sendMessage(ipp + "#" + trm);
}
}
};
static Handler startMessageClose = new Handler();
static Runnable runnableMessageClose = new Runnable() {
#Override
public void run() {
if (client != null) {
client.sendMessage(trm + "IS OFFLINE");
}
}
};
}
The right command for open the connection is new ConnectTask().execute("");
while i'm sending the message with if (client != null) { client.sendMessage(ipp + "#" + trm); }
FinalizingOperationsService.java code:
public class FinalizingOperationsService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("FOService", "Service Started");
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("FOService", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("FOService", "Service Ends");
MainActivity.startConnection.removeCallbacks(MainActivity.runnableConnection);
MainActivity.startConnection.postDelayed(MainActivity.runnableConnection,100);
MainActivity.startMessageClose.removeCallbacks(MainActivity.runnableMessageClose);
MainActivity.startMessageClose.postDelayed(MainActivity.runnableMessageClose,110);
stopSelf();
}
}
Create a new service like this,
public class FinalizingOperationsService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("FOService", "Service Started");
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("FOService", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("FOService", "Service Ends");
// write server updation code here
// after completing code perform stopself() to stop this service;
}
}
And define this service in manifest file like this,
<service android:name=". FinalizingOperationsService" android:stopWithTask="false"/>
Finally start service in onCreate method of your main activity
startService(newIntent(getContext(),FinalizingOperationsService.class));
Explanation:
onTaskRemoved() method of the service is called when application is killed or destroyed, so in this method you can perform your final operations to notify server and stop your service after operations done. Hope it will help you.
I am working on an Android Application which have an one activity class and service class. In service, Continuous bulk data (1090 bytes) will be received every 10 milliseconds. I need to update the text view continuously with these bulk data. What is recommended way to update Text view from a continuous background service?
Service Class
public class RecepService extends Service {
public static Handler mHandler;
StringBuilder hexstring;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
init();
}
private void init() {
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
byte[] readBuf = (byte[]) msg.obj;
int readBuflen = msg.arg1;
// here will receive 1090 bytes of data
// every 10 milliseconds
Receivepatientattributes(readBuf,readBuflen);
}
}
};
}
public void Receivepatientattributes(byte[] readBuf, int len) {
String total_data = "";
total_data = bytetohex(readBuf, len);
MainActivity.recep.setText(MainActivity.recep.getText().toString() + "\t" +
"" + total_data );
}
String bytetohex(byte[] txt, int len) {
String p="";
byte[] text = new byte[len];
text = txt;
hexstring = new StringBuilder();
for (int j = 0; j < len; j++) {
String hex= Integer.toHexString(0xFF & txt[j]);
if (hex.length()==1) {
hexstring.append("0");
}
hexstring.append(hex+" ");
}
p=p+hexstring.toString();
return p;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
If you want to use Schedule and timer task then you can See My Answer
To solve current issue follow this bellow instructions.
Suppose your activity has a Broadcast Receiver
private BroadcastReceiver mReceiver;
Then you override methods onResume() where your broadcast receiver will be registered and also onPause() where will your receiver be unregistered:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter intentFilter = new IntentFilter(
"android.intent.action.MAIN");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract your message from intent
String msg_for_me = intent.getStringExtra("YOUR_MESSAGE");
//log your message value
Log.i("MyTag", msg_for_me);
}
};
//registering your receiver
this.registerReceiver(mReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//unregister your receiver
this.unregisterReceiver(this.mReceiver);
}
Here the broadcast receiver is filtered via android.intent.action.MAIN and from Service the message will BroadCast using this filter
Now your Method Receivepatientattributes will like this :
public void Receivepatientattributes(byte[] readBuf, int len) {
String total_data = "";
total_data = bytetohex(readBuf, len);
Intent i = new Intent("android.intent.action.MAIN").putExtra("YOUR_MESSAGE", total_data);
this.sendBroadcast(i);
}
Thats it. :)
User LocalBroadcastManager
public void Receivepatientattributes(byte[] readBuf, int len) {
String total_data = "";
total_data = bytetohex(readBuf, len);
Intent intent = new Intent("update-text");
// add data
intent.putExtra("message", total_data);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
In MainActivity
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("update-text"));
}
private boolean mCanBeUpdated = true;
private static final int ONE_SEC = 1000; //ms
private static final int RECEPTION_SPEED = 10; //ms
private static final int CYCLES = (int) (ONE_SEC / RECEPTION_SPEED);
private int mCurrentCycle = -1;
private String mMsgCache = "";
// handler for received Intents for the "update-text" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
mMsgCache = mMsgCache + "\t" + message;
if (mCanBeUpdated) {
// No problem updating UI here, refer --> http://stackoverflow.com/a/5676888/1008278
final Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
MainActivity.recep.append(mMsgCache);
mMsgCache = "";
}
});
mCanBeUpdated = false;
} else if (mCurrentCycle >= CYCLES) {
mCurrentCycle = -1;
mCanBeUpdated = true;
} else {
mCurrentCycle++;
}
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
Reference
You can use Timer for Continously updating your textview.
Set value in preferences every time when your service is running with the latest value.
Now in Timer get that value from preferences and update your TextView with that value.
Here is some code :
class UpdateTimeTask extends TimerTask {
public void run() {
textview.setText("updated value");
}
}
Set in onCreate ();
Timer timer = new Timer();
UpdateTimeTask UpdateTimeTask = new UpdateTimeTask ();
timer.schedule(UpdateTimeTask, 1000);
Use handler beacuse A Handler allows communicating back with UI thread from other background thread.
boolean handlerStop = false;
void handleHandler(){
Handler handler =new Handler();
final Runnable r = new Runnable() {
public void run() {
handler.postDelayed(this, 30000);
if(!handlerStop) {
updateTextView() //update your text with other thread like asyncronous thread
}
}
};
handler.postDelayed(r, 0000);
}
#Override
public void onResume() {
super.onResume();
handlerStop=false;
handleHandler();
}
#Override
public void onPause() {
super.onPause();
handlerStop=true;
handleHandler();
}
#Override
public void onStop() {
super.onStop();
handlerStop=true;
handleHandler();
}