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));
}
Related
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 have a problem in my service, the service is runnig from MainActivity (i am doing test) and extends of service.
i want to use the service from foreground and background (when the app is closed) and i already have my first problem:
my service(have a counter that is displayed by LOG) is restarting when i close the app.
also i want to be able to use the service with the open app and close app, in other words to use both the Service Started and Link Service
public class MyService extends Service {
private Thread backgroundThread;
private boolean isRunning;
public MyService() {
Log.e("MyService","constructor");
}
#Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Log.e("onStartCommand","Servicio Llamado");
if (!this.isRunning) {
Log.e("onStartCommand","hilo iniciandose");
this.backgroundThread = new Thread(myTask);
runTask();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("onDestroy","servicio destuido");
}
private void runTask(){
this.isRunning = true;
this.backgroundThread.start();
}
private Runnable myTask = new Runnable() {
public void run() {
Log.e("myTask","hilo iniciado");
int i = 0;
do{
pauseService();
Log.e("myTask","hilo contador: "+i);
//Toast.makeText(getApplicationContext(),"CONTADOR = "+j, Toast.LENGTH_SHORT).show(); //no working :(
i++;
}while (i<10);
/*
//linea de detencion del servicio
//stopSelf();
isRunning=false;
backgroundThread.interrupt();
//backgroundThread = new Thread(myTask);
*/
Log.e("myTask","hilo cerrado");
}
};
private void pauseService(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In main Activity
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("iteraciones",10);
startService(intent);
why because the service restarts when I close the application and how can I avoid it?
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 want to operate two threads in the service.
I want to operate pThread only once in the onCreate
and
I want to continue to operate t-Thread in the onStartCommand.
If two threads operate independently, it works correctly.
but When operating as shown in the following source, it works incorrectly.
Perhaps, t-thread seems to operate before pThread is complete.
I want to t-Thread is operating after pThread is complete.
The source code is below.
public class BeaconService extends Service {
CentralManager centralManager;
private final String SERVER_ADDRESS = "http://xxx.xxx.xxx.xxx";
Handler handler;
XmlParser xmlGetter = new XmlParser();
Thread t;
Thread pThread;
String result = "d5756247-57a2-4344-915d-9599497940a7";
String text;
int count=0;
HashMap<String, Long> key = new HashMap<String, Long>();
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate(){
super.onCreate();
setCentralManager();
handler = new Handler(Looper.getMainLooper());
t = new Thread(new Runnable() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
centralManager.startScanning();
}
});
}
});
pThread = new Thread(new Runnable() {
#Override
public void run() {
try{
URL url = new URL(SERVER_ADDRESS + "/Beacon_Infor.php?");
Log.i("url","url : "+url);
url.openStream();
Log.i("stream","success");
}catch(Exception e){
Log.e("Error", "Error : " + e.getMessage());
}
}
});
pThread.start();
Log.i("Service", "Start");
Toast.makeText(this, "Service Start", Toast.LENGTH_SHORT).show();
key=xmlGetter.getXmlHash("result.xml");
Log.i("beacon hash", "hash : " + key);
}
public int onStartCommand(Intent intent, int flags, int startId){
Log.i("onStartCommand", "Start");
t.start();
return START_STICKY;
}
public void onDestroy(){
Toast.makeText(this, "Service End", Toast.LENGTH_SHORT).show();
if(centralManager.isScanning()) {
centralManager.stopScanning();
}
centralManager.close();
super.onDestroy();
}
}