2017-09-20 45 views
0

我正在嘗試製作一個記錄用戶活動的Android應用程序(例如他觸摸或拖動的位置)。安卓服務文件讀取

由於Android安全性和權限的最近更改,我們無法制作一個應用程序來繪製另一個應用程序並記錄其移動。

所以我們的團隊決定這種方式解決問題

  • ,因爲亞行的shell權限,我們可以使用的logcat和grep工具來分析日誌,找到我們想要的。
  • 創建一個服務,不斷旋轉logcat並保存到一個文件。
  • 創建另一個讀取文件logcat創建,解析和顯示信息的服務。

我們團隊目前存在問題。

我們該如何製作一個不斷讀取文件並將結果吐出的服務?

之後,我們可以更輕鬆地完成其他工作。

回答

2

如在下面的步驟中提到保持運行所有的時間

1)在服務onStartCommand方法的返回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)爲了您的服務,您可能需要通知在關閉後啓動適當的活動。

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)您需要修改清單以啓動單頂模式下的活動。

android:launchMode="singleTop" 

8)請注意,如果系統需要資源並且您的服務不是非常活躍,它可能會被終止。如果這是不可接受的使用startForeground將服務帶到前臺。

startForeground(NOTIFICATION_ID, m_notificationBuilder.build());