【问题标题】:Android app in background后台的安卓应用
【发布时间】:2016-11-06 16:16:18
【问题描述】:

我必须创建应用程序并希望在手机工作时始终使用它,目前我的代码是:

Android 清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.plan.pedometer">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <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:enabled="true"
                 android:name=".PedometerService"/>
        <receiver
            android:name=".receiver.StartPedometerServiceAtBootReceiver"
            android:label="StartPedometerServiceAtBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

StartPedometerServiceAtBootReceiver:

public class StartPedometerServiceAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, PedometerService.class);
            context.startService(serviceIntent);
        }
    }
}

服务:

public class PedometerService extends IntentService {

    private int Steps=0;

    public PedometerService() {
        super("Pedometer_Worker_Thread");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        putInSharedPreferences();
        synchronized (this) {
            try {
                wait(1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void putInSharedPreferences(){
        stepsNumbers = getApplicationContext().getSharedPreferences("stepsData", MODE_PRIVATE);
        editorStepsNumbers=stepsNumbers.edit();
        editorStepsNumbers.putInt(String.valueOf(STEPS),Steps).apply();
    }

}

如果我通过以下方式在MainActivity 中启动Service,它会起作用:

Intent intent = new Intent(getApplication(),PedometerService.class);
                startService(intent);

并且服务在后台运行,但是当我重新启动手机时没有任何反应并且服务没有启动。 我还有一个问题,这是Pedometer 应用程序,我应该将 onSensorChange 方法放在 Service 的哪个位置?在 onHandleIntent() 中创建类似 while(1) 的内容并将其放在那里?

更新 - 我的实际代码是:

我遵循了这个教程https://github.com/codepath/android_guides/wiki/Starting-Background-Services 并尝试使用WakefulBroadcastReceiver AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.plan.pedomoter">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <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="com.plan.pedomoter.MyTestService"
            android:exported="false"/>
        <receiver android:name="com.plan.pedomoter.BootBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

主活动:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    protected void onStart() {
        super.onStart();
        launchTestService();
    }
    public void launchTestService() {
        // Construct our Intent specifying the Service
        Intent i = new Intent(this, MyTestService.class);
        // Add extras to the bundle
        i.putExtra("foo", "bar");
        // Start the service
        startService(i);
    }
}

接收者:

public class BootBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Launch the specified service when this message is received
        Intent startServiceIntent = new Intent(context, MyTestService.class);
        startWakefulService(context, startServiceIntent);
    }
}

服务:

public class MyTestService extends IntentService {
    Handler handler;
    // Must create a default constructor
    public MyTestService() {
        // Used to name the worker thread, important only for debugging.
        super("test-service");
    }
    @Override
    public void onCreate() {
        super.onCreate(); // if you override onCreate(), make sure to call super().
        // If a Context object is needed, call getApplicationContext() here.
        handler = new Handler();
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        WakefulBroadcastReceiver.completeWakefulIntent(intent);
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MyTestService.this, "start", Toast.LENGTH_LONG).show();
                int i = 0;
            }
        });
        int i=0;
        while(true){
            i++;
            // Do some work here
            if(i>1000)
                i=0;
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(MyTestService.this, "stop", Toast.LENGTH_SHORT).show();
    }
}

我在 MyTestService 中使用 while(true) 来检查应用程序是否在后台运行,在项目中我将使用传感器(这是计步器应用程序)然后我想从教程中输入类似 MyAlarmReceiver 的东西来将数据发送到服务器一天几次。

【问题讨论】:

标签: java android android-studio android-sensors


【解决方案1】:

试试这个 Manifest.xml

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

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service android:name=".MyService"/>

        <receiver android:name=".MyBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>


        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

</manifest>

MainActivity

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(getBaseContext(),MyService.class));
    }
}

我的服务

 public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(),"Service started",Toast.LENGTH_LONG).show();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"Service Destroyed",Toast.LENGTH_LONG).show();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

MyBootReceiver

    public class MyBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service  = new Intent(context,MyService.class);
        context.startService(service);
    }
}

我已经测试过应用程序启动服务何时启动,即使您的应用程序被破坏的服务将再次启动。即使重新启动android设备服务也会启动。

第二个问题: 如果要将传感器与服务一起使用,则需要在服务销毁时注册传感器侦听器并注销传感器侦听器,oncreate 方法覆盖传感器对象并创建传感器和传感器管理器。在 onstartCommand 方法中注册生成的传感器侦听器传感器管理器对象,在服务销毁时注销侦听器 你可以检查这个链接 Accelemeter in android

如果你想从服务发送消息到活动,你必须实现 onbind() 方法,活动需要绑定服务检查这个链接 bind activity on service using sensor

bind/unbind service

【讨论】:

  • 嗯检查我的清单文件,有这一行
  • 哦抱歉我没意识到
  • 说实话我还是不知道我的代码有什么问题,有BroadcastReceiver
  • 我将 添加到 Manifest 并更改为完整路径(“.com.pedometer.receiver.StartPedometerServiceAtBootReceiver”),但没有任何反应。找不到任何解决此问题的示例项目...
  • 对不起,我远离电脑,我会尽快检查这个问题,请发布您的所有代码
【解决方案2】:

您好,我有点新,正在寻求帮助,(这不是答案)我无法添加任何其他评论我试图执行一个类似的应用程序,我跟着 mithat 显示,然后当我关闭我的 mobili好像它启动了,但是当我输入手机密码时,它出现了一个系统吐司,上面写着“应用程序停止”,所以我无法得到它。即使我从“最近的应用程序”中扫描应用程序时,它也会显示“应用程序停止” 我想永远运行它, 谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-22
    • 2015-08-16
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多