[Android development diary] explores Android Service for the first time! Service Startup + gravity sensing + pop-up window + keep running, exploring android

Source: Internet
Author: User

[Android development diary] explores Android Service for the first time! Service Startup + gravity sensing + pop-up window + keep running, exploring android
Preface:

I am writing a small program recently. The demand is that the cell phone will pop up as soon as it is shaken. The first time I used the Service, I learned how to use it for two days. I realized a Service pop-up window, started the Service, started and destroyed the Service, and kept the Service running. Meet your own needs. Now we will record our learning experiences. Hope to help you.


1. Service creation: rewrite four methods

  • OnBind (): returns an IBinder object that enables applications to communicate with services. If you use startService or stopService to start or close a Service, the Service and the visitor cannot communicate and exchange data. The onBind () return value is set to null. However, if you want to exchange data, you must use bindService and unbindService to start and close the Service. In this case, onBind () returns a valid IBinder object.
  • OnCreate (): This method is called when the Service is created for the first time.
  • OnStartCommand (): the next generation of onStart. This method is called every time you start a Service through startService (Intent.
  • OnDestroy (): This method is called before the Service is disabled.

package com.service;import android.app.Service;import android.content.Context;import android.content.Intent;import android.util.Log;public class PopupService extends Service {    @Override    public IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;    }            @Override      public void onCreate() {          super.onCreate();          System.out.println("Service is Created");    }       @Override      public int onStartCommand(Intent intent, int flags, int startId) {       System.out.println("Service is Started");                       return START_STICKY;    }    @Override      public void onDestroy() {          super.onDestroy();          System.out.println("Service is Destroyed");    }     }

2. Service configuration: declared in AndroidManifest. xml

<Service android: name = "com. service. PopupService" android: priority = "1000" <! -- Raise the priority --> android: persistent = "true"> <! -- No kill. I don't know if it works. --> <intent-filter> <action android: name = "com. service. POPUP_SERVICE"/> </intent-filter> </service>

3. Start Service: Use BroadcastReceiver

File Creation:

Package com. service; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; public class StartupReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {// start a Service Intent serviceIntent = new Intent (context, PopupService. class); context. startService (serviceIntent );}}

File configuration: declared in AndroidManifest. xml

 <receiver android:name="com.service.StartupReceiver">       <intent-filter>             <action android:name="android.intent.action.BOOT_COMPLETED" />             <category android:name="android.intent.category.LAUNCHER" />       </intent-filter>  </receiver> 

Note permissions:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

4. Start the Service from the Activity:

Use startService (Intent) in the main Activity)

Intent popupintent=new Intent();popupintent.setAction("com.service.POPUP_SERVICE");startService(popupintent);

5. The Service listens to gravity sensing and pops up the window:

  • Here the Sensor. TYPE_ACCELEROMETER accelerometer is used. Similar to other listeners such as gestures, including declarations, registration, and listening
  • The pop-up window uses the activity defined as dialog and notitle by theme.

Code related to the pop-up window:


Intent activityIntent = new Intent (this, SelectFriendsActivity. class); // to start the Activity in the Service, set the following identifier activityIntent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (activityIntent );

Complete code:

Package com. service; import com. task. selectFriendsActivity; import android. app. service; import android. content. context; import android. content. intent; import android. hardware. sensor; import android. hardware. sensorEvent; import android. hardware. sensorEventListener; import android. hardware. sensorManager; import android. OS. IBinder; import android. OS. vibrator; import android. util. log; public class PopupService ext Ends Service implements {// sensorManagerprivate SensorManager sensorManager; private Vibrator vibrator; Intent activityIntent; @ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubreturn null ;} @ Override public void onCreate () {super. onCreate (); System. out. println ("Service is Created"); sensorManager = (SensorManager) getSystemService (Context. SENSOR_S ERVICE); vibrator = (Vibrator) getSystemService (Context. VIBRATOR_SERVICE) ;}@ Override public int onStartCommand (Intent intent, int flags, int startId) {System. out. println ("Service is Started"); // start the service and set serviceon to TRUE. A window is displayed. SelectFriendsActivity. serviceon = true; if (sensorManager! = Null) {// register the listener sensorManager. registerListener (this, sensorManager. getdefasensensor (Sensor. TYPE_ACCELEROMETER), SensorManager. SENSOR_DELAY_NORMAL); // The first parameter is Listener, the second parameter is the sensor type, and the third parameter value obtains the frequency of sensor information.} activityIntent = new Intent (this, SelectFriendsActivity. class); // to start the Activity in the Service, the following identifier must be set: activityIntent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); return START_STICKY ;}@ Override public void o NDestroy () {super. onDestroy (); System. out. println ("Service is Destroyed");}/*** gravity sensing listener */public void onSensorChanged (SensorEvent event) {// execute this method float [] values = event when the sensor information is changed. values; float x = values [0]; // acceleration of gravity in the x axis, float y = values [1] to the right; // acceleration of gravity in the y axis, the forward direction is float z = values [2]; // the acceleration of gravity in the z axis direction, and the upward direction is Log. I ("group", "acceleration of gravity in the x axis" + x + "; acceleration of gravity in the y axis" + y + "; acceleration of gravity in the z axis" + z ); // generally, the gravity is added in these three directions. When the speed reaches 40, the mobile phone is shaken. Int medumValue = 19; // Samsung i9250 cannot shake more than 20. No way, set only 19 if (Math. abs (x)> medumValue | Math. abs (y)> medumValue | Math. abs (z)> medumValue) {if (SelectFriendsActivity. serviceon) {vibrator. vibrate (200); System. out. println ("Service: shaked and popup !!!!!!! "); StartActivity (activityIntent);} else {System. out. println (" Service: shaked only !!!!!!! ") ;}}@ Override public void onAccuracyChanged (Sensor sensor, int accuracy ){}}

The pop-up Activity is a general Activity, but you need to set its size in its xml. In AndroidManifest. xml, set its theme to notitle and dialog type. 

You can use this style:

    <style name="dialogTheme" parent="android:Theme.Dialog">         <item name="android:windowNoTitle">true</item>    </style>

In the pop-up window, you must add the following permissions:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

6. How to keep the Service running without being killed:

Override onDestroy ():

@ Override public void onDestroy () {// super. onDestroy (); // System. out. println ("Service is Destroyed"); System. out. println ("Service is Destroyed, and is Restarted"); Intent localIntent = new Intent (); localIntent. setClass (this, PopupService. class); // Restart Service this upon destruction. startService (localIntent );}

In this way, the Service is always running in the background. 

7. Graphic records:

7.1 start the app, and startService (popupintent) is called in MainActivity );

Result: The onCreate () and onStartCommand () methods in the Service are called in sequence, and the Service starts to run.

7.2 shake mobile phone, Service response pop-up window

Result: The Service runs normally and the gravity sensor runs normally.

7.3 kill the application process, shake the mobile phone, and the Service still responds to the pop-up window

Result: The application process is killed, but the Service still runs normally and the gravity sensor runs normally.

7.4 click the button in avti.pdf in the pop-up window to listen to the Code:

Intent popupintent=new Intent();popupintent.setAction("com.service.POPUP_SERVICE");    stopService(popupintent);
The stopService (Intent) method is called.

Result: The Service is Destroyed, indicating that the onDestroy () method of the Service is called.

7.5 shake the phone again and find that there is still a print output:

Result: although the onDestroy () method is called, its Context is not cleared, and the Service still exists.

7.6 kill all the processes related to this pop-up window, shake the phone again, and find that no output is printed:

Result: The Service is actually stopped once the Context is completely cleared.



I would like to thank newcj for its blog post, Android's comprehensive summary of services, which has benefited me a lot. You can check out the comment area:




I learned how to use Service for the first time. please correct me if there is an error in this article.


 





How can I enable a Service to start automatically on android?

1. First, the system will issue a Standard Broadcast Action, called android. intent. action. BOOT_COMPLETED. This Action will only be sent once after the instance is started. 2. Construct an IntentReceiver class and reconstruct its abstract method onReceiveIntent (Context context, Intent intent) to start the Service you want to start. 3. in AndroidManifest. in xml, add <uses-permission android: name = android. permission. RECEIVE_BOOT_COMPLETED </uses-permission to obtain the use permission of BOOT_COMPLETED, register the previously reconstructed intentcompleer class, and add <actionandroid: name = android in its <intent-filter. intent. action. BOOT_COMPLETED/to capture this Action. Xml: <uses-permission android: name = android. permission. RECEIVE_BOOT_COMPLETED </uses-permission <Cycler android: name =. olympus sreceiver android: label = @ string/app_name <intent-filter <action android: name = android. intent. action. BOOT_COMPLETED/<category android: name = android. intent. category. LAUNCHER/</intent-filter </receiverjava: public class Olympus sreceiver extends IntentReceiver {/* The intent source to be received */static Final String ACTION = android. intent. action. BOOT_COMPLETED; public void onReceiveIntent (Context context, Intent intent) {if (intent. getAction (). equals (ACTION) {context. startService (new Intent (context, Olympus sService. class), null); // starts the Toast countdown service. makeText (context, Olympus sreminder service has started !, Toast. LENGTH_LONG). show () ;}} Note: The current IntentReceiver has changed to BroadcastReceiver, and OnReceiveIntent is onReceive. The java code is as follows: (the application can be automatically started upon startup) public class Olympus sreceiver extends BroadcastReceiver {/* The intent source to receive */static final String ACTION = Android ...... remaining full text>

How does Android Enable Automatic startup of a service?

Today, we will mainly discuss how android can enable a service to automatically start upon startup. The Android mobile phone will trigger a Standard Broadcast Action during startup, called android. intent. action. BOOT_COMPLETED (remember to trigger only once). Here we can build a broadcast receiver to receive this action. next I will briefly write the following implementation steps: 1. First, create a broadcast receiver and reconstruct its abstract method onReceive (Context context, Intent intent ), start the Service you want to start. Import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. util. log; public class BootBroadcastReceiver extends BroadcastReceiver {// rewrite the onReceive method @ Override public void onReceive (Context context, Intent intent) {// XXX. class is the service Intent service to be started = new Intent (context, XXXclass); context. startService (service); Log. v ("TAG", "Automatic startup of the service. .... ") ;}} Configure the xml file, and add the intent-filter configuration in the receiver to add the permission processing class to create the service Processing (XXX) You need to start, and in androidMainfest. add the configuration of (XXX) service to the xml file.

Related Article

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.