如何找到最后一次重启android的时间?

时间:2014-03-28 16:55:45

标签: android service binding

我正在尝试使用service和broadcastreceiver找到最后一次android重启的时间。我的#"广播" class应该在重启后立即记录时间。在" OnCreate"方法a计算的时间,但它不起作用。

我做错了什么?

我的"服务器"类:

public class Server extends Service{

IBinder mBinder = new LocalBinder();

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

public class LocalBinder extends Binder {
    public Server getServerInstance() {
        return Server.this;
    }
} }

我的"客户"类:

public class Client extends Activity {

boolean mBounded;
Server mServer;
TextView text;
Button button;
Broadcast bc = new Broadcast();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

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

    Intent mIntent = new Intent(this, Server.class);
    bindService(mIntent, mConnection, BIND_AUTO_CREATE);

    button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            text.setText(String.valueOf(System.currentTimeMillis() - bc.t));
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    Intent mIntent = new Intent(this, Server.class);
    bindService(mIntent, mConnection, BIND_AUTO_CREATE);
}

ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(Client.this, "Service is disconnected", Toast.LENGTH_LONG).show();
        mBounded = false;
        mServer = null;
    }

    public void onServiceConnected(ComponentName name, IBinder service) {
        Toast.makeText(Client.this, "Service is connected", Toast.LENGTH_LONG).show();
        mBounded = true;
        LocalBinder mLocalBinder = (LocalBinder)service;
        mServer = mLocalBinder.getServerInstance();
    }
};

@Override
protected void onStop() {
    super.onStop();
    if(mBounded) {
        unbindService(mConnection);
        mBounded = false;
    }
}}

"广播"类:

public class Broadcast extends BroadcastReceiver {
public long t;
@Override
public void onReceive(Context context, Intent intent) {
    t = System.currentTimeMillis();
    Intent serviceLauncher = new Intent(context, Server.class);
    context.startService(serviceLauncher);
}}

清单:

<receiver android:name="com.example.serv.Broadcast" android:enabled="true" android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service android:enabled="true" android:name=".Server"/>

1 个答案:

答案 0 :(得分:0)

  

我做错了什么?

可能还没有阅读docs吗?

有一个现成的API,SystemClock.uptimeMillis()

  

返回自启动以来的毫秒数,不计算在深度睡眠中花费的时间

您也可以使用SystemClock.elapsedRealtime()

  

返回自启动以来的毫秒数,包括睡眠时间