如何在启动后启动Android应用程序作为服务

时间:2017-08-28 00:35:17

标签: java android

我试图在初次运行后启动Android应用程序作为后台服务。在第一次运行时,应用程序应该作为普通的Android应用程序启动,然后,它应该是一个后台服务,即使在启动后仍然运行。我写了以下代码。服务类被验证为独立的Android应用程序。但是这个应用程序没有按预期运行。没有错误代码,但是在调试时,服务类不起作用。

清单文件:

<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.tulga.nar.mytrack">

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

<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

最初的一次运行活动类:

package com.tulga.nar.mytrack;
 import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.view.View;

 public class MainActivity extends AppCompatActivity {

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

}
public void starterHandler(View v)
{
 new MyBroadcastReceiver();
}
}

最初一次运行活动类的xml:

 <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tulga.nar.mytrack.MainActivity">

    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/starter"
    android:text="start service"
    android:onClick="starterHandler"/>
    </android.support.constraint.ConstraintLayout>

广播接收器类。单击启动服务按钮后,从MainActivity调用它。它应该启动后台MyService类。

package com.tulga.nar.mytrack;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context aContext, Intent aIntent) {

    // This is where you start your service
    aContext.startService(new Intent(aContext, MyService.class));
}
}

这是后台MyService类。该课程经过验证,可作为独立应用程序使用。但是在这里,代码执行在调试时没有到达这里。

package com.tulga.nar.mytrack;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

 /**
 * Created by Home on 8/27/2017.
 */
  public class MyService extends AppCompatActivity implements 
  LocationListener 
 {
  private class SendDeviceDetails extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {

        String data = "";

        HttpURLConnection connection = null;
        try {
            URL url=new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", 
       "application/json");
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.connect();

            DataOutputStream wr = new 
            DataOutputStream(connection.getOutputStream());

            wr.writeBytes(params[1]);

            wr.flush();
            wr.close();

            InputStream in = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char current = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                data += current;
            }
        } //catch (Exception e) {

        //e.printStackTrace();
        //}
        catch (MalformedURLException e) {
            e.printStackTrace();}
        catch (IOException e) {
            e.printStackTrace();
        }

        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.e("TAG", result); // this is expecting a response code to be 
 sent from your server upon receiving the POST data
    }
 }

 public  static final int RequestPermissionCode  = 1 ;
 static public double myLong=151;
 static public double myLat=-34;
 static public String _id=null;
 static public String _rev=null;

 Button buttonEnable, buttonGet ;
 TextView textViewLongitude, textViewLatitude ;
 Context context;
Intent intent1 ;
Location location;
LocationManager locationManager ;
boolean GpsStatus = false ;
Criteria criteria ;
String Holder;

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

    EnableRuntimePermission();

    locationManager = (LocationManager) 
    getSystemService(Context.LOCATION_SERVICE);

    criteria = new Criteria();

    Holder = locationManager.getBestProvider(criteria, false);

    context = getApplicationContext();
    CheckGpsStatus();
   JSONObject postData = new JSONObject();
    try {
        postData.put("_id",String.valueOf("9876543210"));
        postData.put("Lat", 
   String.valueOf(String.valueOf(MyService.myLat)));
        postData.put("Long", 
    String.valueOf(String.valueOf(MyService.myLong)));
        postData.put("_rev",String.valueOf("1-
    62076042d87cacd2711268d4a396129b"));
        new SendDeviceDetails().execute("my-server-name/mydatabase", 
    postData.toString());

    }
    catch (JSONException e) {
        e.printStackTrace();
    }

}

@Override
public void onLocationChanged(Location location) {

    textViewLongitude.setText("Longitude:" + location.getLongitude());
    textViewLatitude.setText("Latitude:" + location.getLatitude());
    myLong=location.getLongitude();
    myLat=location.getLatitude();

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

public void CheckGpsStatus(){

    locationManager = 
 (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

    GpsStatus = 
 locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

}

public void EnableRuntimePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(MyService.this,
            Manifest.permission.ACCESS_FINE_LOCATION))
    {

        Toast.makeText(MyService.this,"ACCESS_FINE_LOCATION permission 
    allows us to Access GPS in app", Toast.LENGTH_LONG).show();

    } else {

        ActivityCompat.requestPermissions(MyService.this,new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION}, 
  RequestPermissionCode);

    }
}

@Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) 
{

    switch (RC) {

        case RequestPermissionCode:

            if (PResult.length > 0 && PResult[0] == 
   PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(MyService.this,"Permission Granted, Now your 
  application can access GPS.", Toast.LENGTH_LONG).show();

            } else {

                Toast.makeText(MyService.this,"Permission Canceled, Now your 
   application cannot access GPS.", Toast.LENGTH_LONG).show();

            }
            break;
    }
 }

1 个答案:

答案 0 :(得分:2)

你没有在mainifest中收集你的serice,而你的broadcastReceiver也不在正确的地方。它应该是这样的:

&#13;
&#13;
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tulga.nar.mytrack">

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


    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service android:name=".service.MyService">
            <intent-filter>
                <action android:name="write your action name" />
            </intent-filter>
        </service>
    </application>

</manifest>
&#13;
&#13;
&#13;