Android Service do not working -
my app follow next scenarios...
1.[main activity]
- thread repeat sleep(5000)
- if thread sleep(), startservice()
2.[service.class] sendbroadcast()
3.[main activity - broadcastreceiver] toast()
thread working clean, service don't called.
i register in manifest.xml
and create broadcastreceiver dynamic.
manifest.xml
<application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <service android:name=".service" android:enabled="true" /> </application>
mainactivity.java
public class mainactivity extends actionbaractivity implements runnable { thread mthread; boolean msleep = false; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); log.d("activity", "oncreate()"); } @override protected void onstart() { super.onstart(); log.d("activity", "onstart()"); mthread = new thread(this); mthread.start(); } @override public void run() { log.d("thread", "run()"); while(true) { try { mthread.sleep(5000); } catch (interruptedexception e) { //empty } log.d("thread", "sleep"); msleep = true; log.d("thread1", msleep.tostring()); context context = getapplicationcontext(); context.startservice(new intent(mainactivity.this, service.class)); msleep = false; log.d("thread2", msleep.tostring()); } } @override protected void onresume() { super.onresume(); log.d("activity", "onresume()"); log.d("is main thread?", mthread.currentthread().getname()); intentfilter filter = new intentfilter(); //no action registerreceiver(mbroadcastreceiver, filter); } @override protected void onpause() { super.onpause(); log.d("activity", "onpause()"); unregisterreceiver(mbroadcastreceiver); } broadcastreceiver mbroadcastreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { toast.maketext(context, "sleep sleep sleep", toast.length_short).show(); } }; }
service.class
public class service extends android.app.service { @override public void oncreate() { super.oncreate(); log.d("service", "oncreate()"); intent intent = new intent(); sendbroadcast(intent); } @override public int onstartcommand(intent intent, int flags, int startid) { sendbroadcast(intent); return start_sticky; } @override public ibinder onbind(intent intent) { log.d("service", "onbind()"); return null; } }
check package imported, service here not android.app.service
context.startservice(new intent(mainactivity.this, service.class));
Comments
Post a Comment