android服务文件读取

android service file read

我正在尝试制作一个 Android 应用程序来记录用户的 activity(例如他触摸或拖动的位置)。

由于最近在 Android 安全和权限方面发生了变化,我们无法制作一个可以覆盖另一个应用并记录其移动的应用。

所以我们团队决定这样解决问题

我们的团队目前有问题。

我们如何做一个不断读取文件并吐出结果的服务?

之后我们可以更轻松地完成其他工作。

您可以按照以下步骤创建服务,以一直保持服务 运行

1) 在服务的onStartCommand方法中return START_STICKY.

public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

2)使用 startService(MyService) 在后台启动服务,这样无论绑定的客户端有多少,它都始终保持活动状态。

Intent intent = new Intent(this, PowerMeterService.class);
startService(intent);

3)创建活页夹。

public class MyBinder extends Binder {
    public MyService getService() {
            return MyService.this;
    }
}

4)定义一个服务连接。

private ServiceConnection m_serviceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
            m_service = ((MyService.MyBinder)service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
            m_service = null;
    }
};

5)使用 bindService 绑定到服务。

Intent intent = new Intent(this, MyService.class);
bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);

6) 对于您的服务,您可能需要在关闭后启动相应 activity 的通知。

private void addNotification() {
    // create the notification
    Notification.Builder m_notificationBuilder = new Notification.Builder(this)
            .setContentTitle(getText(R.string.service_name))
            .setContentText(getResources().getText(R.string.service_status_monitor))
            .setSmallIcon(R.drawable.notification_small_icon);

    // create the pending intent and add to the notification
    Intent intent = new Intent(this, MyService.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    m_notificationBuilder.setContentIntent(pendingIntent);

    // send the notification
    m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build());
}

7)您需要修改清单以在单顶模式下启动activity。

android:launchMode="singleTop"

8)请注意,如果系统需要资源并且您的服务不是很活跃,它可能会被终止。如果这是不可接受的,请使用 startForeground 将服务带到前台。

startForeground(NOTIFICATION_ID, m_notificationBuilder.build());