Interaction between the service and the control interface (Activity) --- imitation qq Background Service (1), activity background

Source: Internet
Author: User

Interaction between the service and the control interface (Activity) --- imitation qq Background Service (1), activity background

Qq's background service. After we press 2 to return to the app and exit the app, the message will pop up and break through the screen lock, light up the screen, and see the message pop-up box. We can perform a series of operations later. Qq's service will not be killed by 360. It belongs to what we call rogue software. It will steal traffic in the background. Only users can manually close it in the application. The demo I wrote does not have the functionality of this rogue software for the time being. If you have business requirements in the future, you may add the demo about screen unlocking, different mobile phone unlocking methods are different in the Maze unlocking, password unlocking... however, the system can be unlocked. Another reason is that this version has not broken through the pop-up box after the lock screen. This feature will be available in the next version and I will continue to update it. So much nonsense, let's go to the code.

Business Requirements:

1. There is an interface with these elements:
Stop Button
Start button
Reset button
Progress bar 0%-100%
2. There is a service in the background, which includes the following logic:
There is a progress value. The initial value is 0%, the minimum value is 0%, and the maximum value is 100%.
The initial status is stopped and nothing is done.
After receiving the start command, the progress is increased by 1% per second.
After you receive the Stop command, stop the progress and keep the current value.
After receiving the reset command, adjust the progress to 0%
3. The interaction logic between the interface and the service is expressed as follows:
Open the interface and the progress bar is 0.
Start from, the service starts to follow the internal logic, and notifies the interface to update the progress bar control.
Point stop, the Progress logic in the service stops
If you exit the page when the Progress reaches 20% (Home key, return, screen-out, return + screen-out) and wait for 10 seconds before entering, you should see that the progress bar is at 30%, and still walking
Reset at the stop time point. The progress bar on the interface should return to 0% instantly and stay at 0%
Reset the time point. The progress bar on the interface should return to 0% instantly and continue

<Span style = "font-size: 12px;"> package com. example. localservice; import android. app. activity; import android. app. keyguardManager; import android. app. keyguardManager. keyguardLock; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. OS. bundle; import android. OS. powerManager; import android. util. log; import Droid. view. view; import android. view. view. onClickListener; import android. view. windowManager; import android. widget. button; import android. widget. progressBar; import android. widget. textView; public class MainActivity extends Activity implements OnClickListener, Ctroller {private static final String TAG = "MainActivity"; private ProgressBar progressBar; private Button startBtn; private Button stopBtn; privat E Button resetBtn; private TextView tx; private Intent intent = new Intent (); private UpdateReceiver updateReceiver; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // dynamically register the broadcast receiver updateReceiver = new UpdateReceiver (); IntentFilter intentFilter = new IntentFilter (); intentFilter. addAction ("com. example. localservice. UPDA TE "); registerReceiver (updateReceiver, intentFilter); progressBar = (ProgressBar) findViewById (R. id. progressBar); startBtn = (Button) findViewById (R. id. start); stopBtn = (Button) findViewById (R. id. stop); resetBtn = (Button) findViewById (R. id. reset); tx = (TextView) findViewById (R. id. tx); startBtn. setOnClickListener (this); stopBtn. setOnClickListener (this); resetBtn. setOnClickListener (this); Intent in = new Intent (this, MyService. class); startService (in); // start the system and send a broadcast. setAction ("com. example. localservice. NOTIFICATION "); intent. putExtra ("click", "data"); sendBroadcast (intent) ;}@ Overridepublic void onClick (View v) {switch (v. getId () {case R. id. start: intent. setAction ("com. example. localservice. NOTIFICATION "); intent. putExtra ("click", "start"); sendBroadcast (intent); break; case R. id. stop: intent. setAction ("Com. example. localservice. NOTIFICATION "); intent. putExtra ("click", "stop"); sendBroadcast (intent); break; case R. id. reset: intent. setAction ("com. example. localservice. NOTIFICATION "); intent. putExtra ("click", "reset"); sendBroadcast (intent); break;} public class UpdateReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {// get the progress and update UI int progress = intent. getIntE Xtra ("progress", 0); progressBar. setProgress (progress); tx. setText (progress + "%"); if (progress % 10 = 0) {SoundManager. getInstance (context ). playSound (SoundManager. NETERROR);} else {SoundManager. getInstance (context ). stopSound () ;}if (progress % 20 = 0) {lighten () ;}else {}}@ Overrideprotected void onPause () {super. onPause (); MyService. IS_DESTORY = false;} @ Overrideprotected void onResume () {supe R. onResume (); MyService. IS_DESTORY = false;} @ Overrideprotected void onDestroy () {super. onDestroy (); unregisterReceiver (updateReceiver); SoundManager. getInstance (this ). stopSound (); MyService. IS_DESTORY = true; Log. I (TAG, "------> onDestroy");}/*** light up the screen */public void lighten () {PowerManager pm = (PowerManager) getSystemService (Context. POWER_SERVICE); if (! Pm. isScreenOn () {// obtain the power manager object PowerManager. wakeLock wl = pm. newWakeLock (PowerManager. ACQUIRE_CAUSES_WAKEUP | PowerManager. SCREEN_DIM_WAKE_LOCK, "bright"); // light the screen wl. acquire (); if (! MyService. IS_DESTORY) {// unlock getWindow (). addFlags (WindowManager. layoutParams. FLAG_DISMISS_KEYGUARD);} else {// obtain the power manager object KeyguardManager km = (KeyguardManager) getSystemService (Context. KEYGUARD_SERVICE); // obtain the KeyguardLock kl = km. newKeyguardLock ("unLock"); // unLock kl. disableKeyguard (); // kl. reenableKeyguard (); // enable automatic lock again // wl. release (); // release }}@ Overridepublic void dismissKeyguard () {getWindow (). addFlags (WindowManager. layoutParams. FLAG_DISMISS_KEYGUARD) ;}@ Overridepublic void runOnUI (Runnable run) {runOnUiThread (run) ;}</span>
<Span style = "font-size: 12px;"> package com. example. localservice; import android. app. keyguardManager; import android. app. keyguardManager. keyguardLock; import android. app. service; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. OS. bundle; import android. OS. handler; import android. OS. IBinder; import androi D. OS. message; import android. OS. powerManager; import android. provider. settings; import android. text. textUtils; import android. view. windowManager; public class MyService extends Service {public static final int MAX_PROGRESS = 100; private int progress = 0; private ServiceReciver serviceReciver; private int OK = 0; public static boolean IS_DESTORY = false; private Ctroller object; @ Overridepublic IBinder onBin D (Intent intent) {return null;} @ Overridepublic void onCreate () {super. onCreate (); // dynamically register the broadcast receiver serviceReciver = new ServiceReciver (); IntentFilter intentFilter = new IntentFilter (); intentFilter. addAction ("com. example. localservice. NOTIFICATION "); registerReceiver (serviceReciver, intentFilter) ;}@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {// TODO Auto-generated method stubr Eturn super. onStartCommand (intent, flags, startId) ;}@ Overridepublic void onDestroy () {super. onDestroy (); unregisterReceiver (serviceReciver);}/*** simulate download task, updated every second */public void startDownLoad () {new Thread (new Runnable () {@ Overridepublic void run () {while (OK <MAX_PROGRESS) {OK + = 1; progress + = 1; // send Action as com. example. localservice. UPDATE broadcast if (IS_DESTORY) {Intent intent = new Intent (MyService. this, MainActivity. class); intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (intent); Intent in = new Intent (); in. putExtra ("progress", progress); in. setAction ("com. example. localservice. UPDATE "); sendBroadcast (in);} else {Intent in = new Intent (); in. putExtra ("progress", progress); in. setAction ("com. example. localservice. UPDATE "); sendBroadcast (in);} try {Thread. sleep (500);} catch (InterruptedException E) {e. printStackTrace () ;}// if (progress % 20 = 0) {// lighten (); // setBrightness ();//}}}}). start () ;}public void stop () {Intent in = new Intent (); in. putExtra ("progress", progress); in. setAction ("com. example. localservice. UPDATE "); sendBroadcast (in);} public void reset () {progress = 0; Intent in = new Intent (); in. putExtra ("progress", progress); in. setAction ("com. example. localservice. UPDATE "); sendBroadcast (In);} public class ServiceReciver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {String extra = intent. getStringExtra ("click"); if ("data ". equals (extra) {Intent in = new Intent (); in. putExtra ("progress", progress); in. setAction ("com. example. localservice. UPDATE "); sendBroadcast (in);} if (" start ". equals (extra) {// myThread. start (); OK = progress; startDownLoad () ;} If ("stop ". equals (extra) {OK = 101; stop () ;}if ("reset ". equals (extra) {reset () ;}}//// brightness change // public static void SetLightness (Activity act, int value) {// try {// System. putInt (act. getContentResolver (), System. SCREEN_BRIGHTNESS, // value); // WindowManager. layoutParams lp = act. getWindow (). getAttributes (); // lp. screenBrightness = (value <= 0? 1: value)/255f; // act. getWindow (). setAttributes (lp); //} catch (Exception e) {// Toast. makeText (act, "brightness cannot be changed", Toast. LENGTH_SHORT ). show (); //} // obtain the brightness // public static int GetLightness (Activity act) {// return System. getInt (act. getContentResolver (), // System. SCREEN_BRIGHTNESS,-1); //}/*** light up screen */public void lighten () {PowerManager pm = (PowerManager) getSystemService (Context. POWER_SERVICE); if (! Pm. isScreenOn () {// obtain the power manager object PowerManager. wakeLock wl = pm. newWakeLock (PowerManager. ACQUIRE_CAUSES_WAKEUP | PowerManager. SCREEN_DIM_WAKE_LOCK, "bright"); // light the screen wl. acquire (); if (! IS_DESTORY) {// unlock // kl. disableKeyguard ();} else {Intent intent = new Intent (this, MainActivity. class); intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (intent); // get the power manager object KeyguardManager km = (KeyguardManager) getSystemService (Context. KEYGUARD_SERVICE); // obtain the KeyguardLock kl = km. newKeyguardLock ("unLock"); // unLock kl. disableKeyguard (); // kl. reenableKeyguard (); // enable automatic lock again // wl. release (); // release }}/ *** change screen brightness */protected void setBrightness () {WindowManager. layoutParams lp = (MainActivity) object ). getWindow (). getAttributes (); int brightness = Settings. system. getInt (MainActivity) object ). getContentResolver (), Settings. system. SCREEN_BRIGHTNESS, 0); // if (brightness <217) // lp. screenBrightness = 0.85f; // else // brightness + = 10; // if (brightness> 255) // brightness = 60; lp. screenBrightness = brightness/255.0f; (MainActivity) object ). getWindow (). setAttributes (lp); Settings. system. putInt (MainActivity) object ). getContentResolver (), Settings. system. SCREEN_BRIGHTNESS, brightness) ;}</span>
A new requirement is added later. If the progress bar goes to 10.20.30.40.50.60.70.80, 90.100, a prompt will be sent. If the progress bar is running to 201740.60.80.100, the screen is lit and unlocked. In fact, in the updateReceiver
<span style="font-size:12px;">if(progress % 10 == 0){            SoundManager.getInstance(context).playSound(SoundManager.NETERROR);            }else{            SoundManager.getInstance(context).stopSound();            }                        if(progress % 20 == 0){            lighten();            }else {                        }</span>
It should be better to put it in the service. I am relatively lazy. I haven't changed it in the demo. Well, it's so much now. Please wait for the next version. : Http://download.csdn.net/detail/u012301841/8250881

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.