Android将定位服务封装为Service

来源:互联网 发布:跳跃网络充值 编辑:程序博客网 时间:2024/04/29 04:32

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private Button startService;    private Button stopService;    private EditText editText=null;    private MyReceiver receiver=null;    private EditText username, password, positionName;    private SQLiteDatabase DB;    private ListView values;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        username = (EditText) findViewById(R.id.username);        password = (EditText) findViewById(R.id.userpwd);        positionName = (EditText) findViewById(R.id.positionName);        values = (ListView) findViewById(R.id.values_list);        DB = SQLiteDatabase.openOrCreateDatabase(getFilesDir() + "/info.db",                null);        editText=(EditText)findViewById(R.id.editText);        startService = (Button) findViewById(R.id.start_service);        stopService = (Button) findViewById(R.id.stop_service);        startService.setOnClickListener(this);        stopService.setOnClickListener(this);        // 长按删除        values.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {            @Override            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,                                           int arg2, long arg3) {                // 获取所点击项的_id                TextView tv = (TextView) arg1.findViewById(R.id.tv_id);                final String id = tv.getText().toString();                // 通过Dialog提示是否删除                AlertDialog.Builder builder = new AlertDialog.Builder(                        MainActivity.this);                builder.setMessage("确定要删除吗?");                // 确定按钮点击事件                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        delete(id);                        replaceList();// 删除后刷新列表                    }                });                // 取消按钮点击事件                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        dialog.dismiss();                    }                });                builder.create().show();                return true;            }        });        // 点击更新        values.setOnItemClickListener(new AdapterView.OnItemClickListener() {            @Override            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,                                    long arg3) {                // 获取_id,username,password项                TextView tvId = (TextView) arg1.findViewById(R.id.tv_id);                TextView tvName = (TextView) arg1                        .findViewById(R.id.tv_username);                TextView tvPass = (TextView) arg1                        .findViewById(R.id.tv_password);                TextView tvPName = (TextView) arg1                        .findViewById(R.id.tv_positionName);                final String id = tvId.getText().toString();                String username = tvName.getText().toString();                String password = tvPass.getText().toString();                String positionName = tvPName.getText().toString();                // 通过Dialog弹出修改界面                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);                builder.setTitle("修改");                // 自定义界面包括两个文本输入框                View v = View.inflate(MainActivity.this, R.layout.alertdialog,                        null);                final EditText etName = (EditText) v                        .findViewById(R.id.alert_name);                final EditText etPass = (EditText) v                        .findViewById(R.id.alert_pass);                final EditText etPName = (EditText) v                        .findViewById(R.id.alert_positionName);                // Dialog弹出就显示原内容                etName.setText(username);                etPass.setText(password);                etPName.setText(positionName);                builder.setView(v);                // 确定按钮点击事件                builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        String newName = etName.getText().toString();                        String newPass = etPass.getText().toString();                        String newPName = etPName.getText().toString();                        updata(newName, newPass, id, newPName);                        replaceList();// 更新后刷新列表                    }                });                // 取消按钮点击事件                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        dialog.dismiss();                    }                });                builder.create().show();            }        });    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.start_service:                Intent startIntent = new Intent(this, MyService.class);                startService(startIntent); // 启动服务                //注册广播接收器                receiver=new MyReceiver();                IntentFilter filter=new IntentFilter();                filter.addAction("com.example.liwenxiao.myservice");                MainActivity.this.registerReceiver(receiver,filter);                break;            case R.id.stop_service:                Intent stopIntent = new Intent(this, MyService.class);                stopService(stopIntent); // 停止服务                username.setText("");                password.setText("");                positionName.setText("");                editText.setText("");                break;            default:                break;        }    }    //获取广播数据    public class MyReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            Bundle bundle=intent.getExtras();            Double latitude=bundle.getDouble("latitude");            Double longitude=bundle.getDouble("longitude");            editText.setText(latitude + " "+longitude);            username.setText(latitude+"");            password.setText(longitude+"");        }    }    /**     * 关闭程序关闭数据库     */    @Override    protected void onDestroy() {        super.onDestroy();        DB.close();    }    /**     * 保存按钮点击事件,首次插入由于没有表必然报错,简化程序利用try-catch在catch中创建表     */    public void save(View v) {        String name = username.getText().toString();        String pass = password.getText().toString();        String pName = positionName.getText().toString();        try {            insert(name, pass, pName);        } catch (Exception e) {            create();            insert(name, pass, pName);        }        Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();        // username.setText("");        // password.setText("");        // positionName.setText("");    }    /**     * 读取按钮点击事件,以列表的形式显示所有内容     */    public void read(View v) {        replaceList();    }    /**     * ListView的适配器     */    public void replaceList() {        Cursor cursor = select();        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,                R.layout.values_item, cursor, new String[]{"_id", "positionName", "username",                "password"}, new int[]{R.id.tv_id, R.id.tv_positionName, R.id.tv_username,                R.id.tv_password},                SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);        values.setAdapter(adapter);    }    /**     * 建表     */    public void create() {        String createSql = "create table loction(_id integer primary key autoincrement,username,password,positionName)";        DB.execSQL(createSql);    }    /**     * 插入     */    public void insert(String username, String password, String positionName) {        String insertSql = "insert into loction(username,password,positionName) values(?,?,?)";        DB.execSQL(insertSql, new String[]{username, password, positionName});    }    /**     * 查询     */    public Cursor select() {        String selectSql = "select _id,username,password,positionName from loction";        Cursor cursor = DB.rawQuery(selectSql, null);// 我们需要查处所有项故不需要查询条件        return cursor;    }    /**     * 删除     */    public void delete(String id) {        String deleteSql = "delete from loction where _id=?";        DB.execSQL(deleteSql, new String[]{id});    }    /**     * 更新     */    public void updata(String username, String password, String id, String positionName) {        String updataSql = "update loction set username=?,password=? ,positionName=? where _id=?";        DB.execSQL(updataSql, new String[]{username, password, positionName, id});    }}

MyService.java

import android.Manifest;import android.app.Service;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Binder;import android.os.Bundle;import android.os.IBinder;import android.support.annotation.Nullable;import android.support.v4.app.ActivityCompat;import android.util.Log;import android.widget.Toast;import java.util.List;/** * Created by LiWenxiao on 2017/4/19. */public class MyService extends Service {    private LocationManager locationManager;    private String provider;    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        locationManager = (LocationManager) getSystemService(Context.                LOCATION_SERVICE);        // 获取所有可用的位置 供器        List<String> providerList = locationManager.getProviders(true);        if (providerList.contains(LocationManager.GPS_PROVIDER)) {            provider = LocationManager.GPS_PROVIDER;        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {            provider = LocationManager.NETWORK_PROVIDER;        } else {            // 当没有可用的位置 供器时,弹出Toast 示用户            Toast.makeText(this, "No location provider to use",                    Toast.LENGTH_SHORT).show();            return;        }        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {            // TODO: Consider calling            //    ActivityCompat#requestPermissions            // here to request the missing permissions, and then overriding            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,            //                                          int[] grantResults)            // to handle the case where the user grants the permission. See the documentation            // for ActivityCompat#requestPermissions for more details.            return;        }        Location location = locationManager.getLastKnownLocation(provider);        if (location != null) {            // 显示当前设备的位置信息            // 发送广播            Intent intent = new Intent();            Double latitude=location.getLatitude();            Double longitude=location.getLongitude();            intent.putExtra("latitude", latitude);            intent.putExtra("longitude",longitude);            intent.setAction("com.example.liwenxiao.myservice");            sendBroadcast(intent);        }        locationManager.requestLocationUpdates(provider, 1000, 1, locationListener);    }    LocationListener locationListener = new LocationListener() {        @Override        public void onStatusChanged(String provider, int status, Bundle                extras) {        }        @Override        public void onProviderEnabled(String provider) {        }        @Override        public void onProviderDisabled(String provider) {        }        @Override        public void onLocationChanged(Location location) {            // 更新当前设备的位置信息            // 发送广播            Intent intent = new Intent();            Double latitude=location.getLatitude();            Double longitude=location.getLongitude();            intent.putExtra("latitude", latitude);            intent.putExtra("longitude",longitude);            intent.setAction("com.example.liwenxiao.myservice");            sendBroadcast(intent);        }    };    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.d("MyService", "onStartCommand executed");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        if (locationManager != null) {            // 关闭程序时将监听器移除            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {                // TODO: Consider calling                //    ActivityCompat#requestPermissions                // here to request the missing permissions, and then overriding                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,                //                                          int[] grantResults)                // to handle the case where the user grants the permission. See the documentation                // for ActivityCompat#requestPermissions for more details.                return;            }            locationManager.removeUpdates(locationListener);        }        Log.d("MyService", "onDestroy executed");    }}

清单文件

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.liwenxiao.myservice">    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".MyService" > </service>    </application>    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /></manifest>

布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <EditText android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:cursorVisible="false"        android:editable="false"        android:id="@+id/editText"/>    <Button        android:id="@+id/start_service"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Start Service" />    <Button        android:id="@+id/stop_service"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Stop Service" />    <EditText        android:id="@+id/positionName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="PositionName" />    <EditText        android:id="@+id/username"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Latitude" />    <EditText        android:id="@+id/userpwd"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Longitude" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="save"        android:text="SAVE" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="read"        android:text="READ" />    <ListView        android:id="@+id/values_list"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>

alertdialog.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="PositionName" />        <EditText            android:id="@+id/alert_positionName"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Latitude" />        <EditText            android:id="@+id/alert_name"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Longitude" />        <EditText            android:id="@+id/alert_pass"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </LinearLayout></LinearLayout>

values_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <TextView        android:id="@+id/tv_id"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20sp"        android:visibility="gone" />    <TextView        android:id="@+id/tv_positionName"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="10dp"        android:textSize="20sp" />    <TextView        android:id="@+id/tv_username"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="10dp"        android:textSize="20sp" />    <TextView        android:id="@+id/tv_password"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="20dp"        android:textSize="20sp" /></LinearLayout>
0 0
原创粉丝点击