簡體   English   中英

讓應用始終在 Android 的后台運行

[英]Keep app running in background on Android all the time

我必須獲取人們的軌跡(例如從家到工作),因此我的應用程序獲取緯度和經度(我有兩個按鈕:1. 開始獲取緯度和經度 2. 停止獲取緯度和經度)。 但是,我希望 android 不會終止應用程序,我希望在用戶使用 facebook、twitter(例如)或只是用戶鎖定他的智能手機時保持我的應用程序運行。 當用戶在使用 facebook 或 twitter(例如)時使用該應用程序時,我的應用程序運行良好,但是當我鎖定我的智能手機時,Android 會終止該應用程序。 我曾嘗試使用 intentservice 和 service,但是當我鎖定屏幕時它們不起作用。 我應該使用 PowerManager.WakeLock 嗎? 我不完全知道它是如何工作的以及它的作用。

這是我嘗試服務的一個例子,我不知道我是否錯了,但它在以下情況下不起作用:1.我在應用程序中(我已經啟動了服務)2.我點擊主頁按鈕(同時服務正在運行) 3. 我鎖定屏幕。 4.然后服務和應用程序被android殺死(服務沒有完成它的東西)

顯現

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

    <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"
            android:exported="false"></service>

    </application>

</manifest>

活動主

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.javosoft.intentservice.MainActivity">

    <Button
        android:text="start Service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:id="@+id/button"
        android:onClick="startService"/>

    <Button
        android:text="Stop Service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/button"
        android:layout_alignStart="@+id/button"
        android:layout_marginBottom="68dp"
        android:id="@+id/button2"
        android:onClick="stopService" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="textito :D"
        android:ems="10"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/editText" />
</RelativeLayout>

布局

主要活動

package com.javosoft.intentservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button button;

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

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });

    }

    public void stopService (View view){
        Intent intent = new Intent(this, MyService.class);
        stopService(intent);
    }
}

我的服務類

package com.javosoft.intentservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    final class MyThreadClass implements Runnable{

        int service_id;
        MyThreadClass(int service_id){
            this.service_id = service_id;
        }

        @Override
        public void run() {

            synchronized (this){
                int count = 0;
                while (count < 10){
                    Log.i("servicio", "while: " + String.valueOf(count));
                    try {
                        wait(2000);
                        count++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            stopSelf(service_id);

        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "El servició ha empezado D:", Toast.LENGTH_SHORT).show();
        Log.i("servicio", "El servició ha empezado D:");


        Log.i("servicio", "onStartCommand arriba");

        Thread thread = new Thread(new MyThreadClass(startId));
        thread.start();

        Log.i("servicio", "onStartCommand abajo");
        return START_STICKY;
        //return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        //super.onDestroy();
        Toast.makeText(this, "El servicio ha padarado ._.", Toast.LENGTH_SHORT).show();
        Log.i("servicio", "El servicio ha padarado ._.");
    }

    //@Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;

    }
}

試試我們的這個

public class ForegroundService extends Service {
    private static final String LOG_TAG = "ForegroundService";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // Your logical code here

        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {

        //When remove app from background then start it again
        startService(new Intent(this, ForegroundService.class));

        super.onTaskRemoved(rootIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG_TAG, "In onDestroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Used only in case of bound services.
        return null;
    }
}

在開始按鈕上單擊:

Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
    startService(startIntent);

在清單中

<service
            android:name=".ForegroundService"
            android:enabled="true"
            android:stopWithTask="false" />

我讀過一些智能手機存在此類問題,我發現華為、小米等在實施服務方面存在問題,猜猜看:我的智能手機是華為。 問題出在這些設備上預裝的節能程序。 因此,我嘗試在 Nexus(此模擬器)、Sony 和 Moto G 上運行我的程序,該程序在這 3 台設備上運行良好。 感謝幫助。

正如@Gudin 所說,在我看來,您在 20 秒后停止服務。 但是,由於您說這有時有效,我猜這只是一些測試代碼。 我懷疑您的問題在於您如何啟動服務。 傳遞活動的上下文意味着您的服務與該活動的生命周期相關聯。 如果它被破壞了,我認為你的服務會隨之而來。 (簡單地通過 Activity 的onStop()而不是onDestroy()使 Service 完好無損)。 嘗試這個

    Intent intent = new Intent(getApplicationContext(), MyService.class);

我嘗試復制你的問題,但不能,所以我不能肯定這是你的問題。 不過,這是一個很好的起點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM