Some cluttered knowledge points (3)

Some cluttered knowledge points in Android (3)

1. Define style to extract xml attributes of View

Sometimes every Child in a layout has the same style, so it's too redundant to rewrite many identical attributes each time. So, extract these attributes and define them into style, as follows

<!-- This is the style of the sideslip menu.    Extract
 -->
<style name="style_bt_text" parent="android:Widget.Holo.Light.TextView">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background"></item>
    <item name="android:background">@drawable/selector_menu_bt_bg</item>
    <item name="android:drawablePadding">10dp</item>
</style>

Then when using the style, you can write as follows:

 <TextView
        style="@style/style_bt_text"
        android:drawableLeft="@drawable/tab_news"
        android:text="Journalism"/>

2. Picture selector

In the process of selecting and unchecking, switch the display image (e.g. Button pressed and unchecked)

Find the appropriate location in the api like this: Develop - > api Guides - > AppResource - > Resource Types - > Drawable - > StateList

selector placement path res/drawable/button.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"
          android:drawable="@drawable/button_pressed" /> <!-- Check the button picture -->
        <item android:state_focused="true"
          android:drawable="@drawable/button_focused" /> <!-- Button to get focus picture -->
        <item android:state_hovered="true"
          android:drawable="@drawable/button_focused" /> <!-- Flat panel TV,Suspension Selection of an Application Picture -->
        <item android:drawable="@drawable/button_normal" /> <!-- Default picture-->
    </selector>

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/button" />

3. Create gesture management objects to manage gesture actions passed in onTouchEvent(event)

Events in onTouchEvent can be easily managed with this object

public class Setup1Activity extends BaseActivity {

    private GestureDetector mGesture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup1);

        /*
            Create gesture management objects to manage gesture actions passed in onTouchEvent(event)
         */
        mGesture = new GestureDetector(this, new GestureDetector
                .SimpleOnGestureListener() {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float
                    velocityY) {
                //Monitor the movement of gestures
                if (e1.getX() - e2.getX() > 0) {
                    //Users want to jump to the next page
                    //Jump to Settings Interface 2
                    Intent intent = new Intent(Setup1Activity.this, Setup2Activity.class);
                    startActivity(intent);

                    finish();
                }

                return true;
            }
        });

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mGesture.onTouchEvent(event);
        return super.onTouchEvent(event);
    }
}

4. Play short music

1. You need to put the resource file under RES / ray, and then

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.ylzs);
mediaPlayer.setLooping(true);   //Set up a circular playback
mediaPlayer.start();   //Start playing

5.Android Screen Monitor Synchronizes Mobile Screen to PC

1. Tools: Android Screen Monitor
2. Download address: https://adakoda.github.io/android-screen-monitor/
perhaps http://download.csdn.net/detail/guidechange4585/6810711
3. Usage: Configure Java environment variables well, because we use jar, so it is more convenient to configure environment variables. If SDK environment variables are well configured, just follow the method on the official website. If not, then: java-jar/data/SDK/sdk/platform-tools/asm.jar.
Then choose your mobile phone.

6. Get the location of mobile phone (GPS mode)

//1. Get the LocationManager object
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //2. Request location
    //Parameter: minTime: update interval minDistance: update distance interval    
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1, 0,new LocationListener(){

        @Override
        public void onLocationChanged(Location location) {
            //Change of position
            Toast.makeText(getApplicationContext(), "Change of position", Toast.LENGTH_SHORT).show();
            double longitude = location.getLongitude();  //longitude
            double latitude = location.getLatitude();    //latitude
            Log.d("xfhy", "longitude = "+longitude+", latitude = "+latitude);
            tv_location.setText("longitude = "+longitude+", latitude = "+latitude);
        } 

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
            //Changes in the status of location providers
            Toast.makeText(getApplicationContext(), "Changes in the status of location providers", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderEnabled(String provider) {
            //Location providers are available
            Toast.makeText(getApplicationContext(), "Location providers are available", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderDisabled(String provider) {
            //Location provider unavailable
            Toast.makeText(getApplicationContext(), "Location provider unavailable", Toast.LENGTH_SHORT).show();
        }

    });

Secondly, authority is required:

<! - The right to acquire accurate GPS coordinates - >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<! - Permission to allow simulators to simulate position coordinates - >
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<! - Access to rough coordinates (used for network positioning) -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

7. Use of Device Manager

1. View google Document Administration - >. device polices Configuration of the manifest file mainfest.xml

<receiver android:name=".app.DeviceAdminSample$DeviceAdminSampleReceiver"
        android:label="@string/sample_device_admin"
        android:description="@string/sample_device_admin_description"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
    <meta-data android:name="android.app.device_admin"
            android:resource="@xml/device_admin_sample" />
    <intent-filter>
        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
    </intent-filter>
</receiver>

2. Create the subclass of mainfest.xml broadcast receiver and inherit DeviceAdmin to DeviceAdminReceiver

3. Repair the errors in the manifest file (string creation, xml file creation)

4. Create the file device_admin_sample.xml under the res/xml folder

    <device-admin xmlns:android="http://schemas.android.com/apk/res/android">
      <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
        <expire-password />
        <encrypted-storage />
        <disable-camera />
      </uses-policies>
    </device-admin>

5. Open the activity of the activation interface

ComponentName mDeviceAdminSample = new ComponentName(context, DeviceAdmin.class);

    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample);
    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
        mActivity.getString(R.string.add_admin_extra_app_text));
    startActivity(intent);

6. One-click activation

A key lock screen must be activated before it can be used.

//Judging the state of activation
    boolean adminActive = mDPM.isAdminActive(mDeviceAdminSample);
    if(adminActive){
        mDPM.lockNow();
        //Setting the password to light the screen again
        //mDPM.resetPassword("1234", 0);
    }else{
        Toast.makeText(this, "Please activate first", 0).show();
    }

7. One-click data clearance

Prerequisite: It must be activated before it can be used

//Determine whether activation is active or not. If data is cleared without activation, an exception is reported.
if(mDPM.isAdminActive(mDeviceAdminSample)){
    mDPM.wipeData(0);   //Clear data from mobile phones
    //MDPM. wipeData (DevicePolicy Manager. WIPE_EXTERNAL_STORAGE); // Data from mobile phones and external storage devices will be cleared
} else {
    Toast.makeText(getApplicationContext(), "Please activate first", Toast.LENGTH_SHORT).show();
}

8. One-click Unloading

  • If it is not activated in Device Manager, it can be uninstalled directly.
  • Activation has been made in the Device Manager, can not be uninstalled, the system will be prompted to cancel the activation in the Device Manager, and then can be uninstalled.
  • Uninstall is the function of Android system, just call the system's unload interface (Activity). Look at the source code, Package Installer. Find the uninstall Activity source code in the manifest file.
    Match the corresponding action, category, data (application package name) to uninstall the specified application.

8.Android Source Interpretation

Download to an Android source code compression file, usually very large, several G. inside, some things are useless, if you just want to see the application package of the system (that is, the source code of the native application), you can look at the path.
android-7.0.0_r1.7z\android-7.0.0_r1\packages

9. Get some paths in the project installation directory

1.getAssets().open(addressDbName); // Get the input stream of addressDbName in the assets of the project

2.getCacheDir(); // Returns the absolute path to the application-specific cache directory on the file system. These files will be the first to be deleted when the device has insufficient storage space. There is no guarantee that these files will be deleted. Note: You shouldn't rely on the system to delete these files for you; you should always have a reasonable maximum, such as 1 MB, to use the space of cached files and trim them when they are out of that space.

3.getFilesDir(); // Returns the absolute path of the directory in the file system where the files created using openFileOutput (String, int) are stored.
There is no need to read or write access to the return path, because the path is internal storage.

Keywords: Android xml MediaPlayer Mobile

Added by Mobile on Fri, 05 Jul 2019 20:36:49 +0300