android監聽應用自身被卸載
在實際開發中,常常需要監聽應用本身是否被卸載或相近的需求。在網上淘了很久都沒有看到實際的做法,最多就給出一個思路,可以通過捕捉系統日志來檢測到這個應用是否被卸載,繼而做相關的操作。
通過監聽Intent.ACTION_PACKAGE_REMOVED意圖只能監聽到其他應用程序是否被卸載,無法監聽自身!
本例子也是通過監聽系統日志,來監聽應用本身是否被卸載。
LogcatObserver.java
public interface LogcatObserver {
public void handleLog(String info);
} </pre><a class="CopyToClipboard" title="copy" href="/misc/goto?guid=4959554432651248629"></a></div>
</div>
</div>
LogcatScannerService.java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class LogcatScannerService extends Service implements LogcatObserver {
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
new AndroidLogcatScannerThread(this).start();
}
@Override
public void handleLog(String info) {
if (info.contains("android.intent.action.DELETE")
&& info.contains(getPackageName())) {
//do something yourself
}
}
private class AndroidLogcatScannerThread extends Thread {
private LogcatObserver mObserver;
public AndroidLogcatScannerThread(LogcatObserver observer) {
mObserver = observer;
}
@Override
public void run() {
String[] cmds = { "logcat", "-c" };
String shellCmd = "logcat";
Process process = null;
InputStream is = null;
DataInputStream dis = null;
String line = "";
Runtime runtime = Runtime.getRuntime();
try {
mObserver.handleLog(line);
int waitValue;
waitValue = runtime.exec(cmds).waitFor();
mObserver.handleLog("waitValue=" + waitValue
+ "\n Has do Clear logcat cache.");
process = runtime.exec(shellCmd);
is = process.getInputStream();
dis = new DataInputStream(is);
while ((line = dis.readLine()) != null) {
if (mObserver != null)
mObserver.handleLog(line);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException ie) {
} finally {
try {
if (dis != null) {
dis.close();
}
if (is != null) {
is.close();
}
if (process != null) {
process.destroy();
}
} catch (Exception e) {
}
}
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
} </pre><a class="CopyToClipboard" title="copy" href="/misc/goto?guid=4959554432651248629"></a></div>
</div>
</div>
調用時只需startService(this,LogcatScannerService.class)既可。
例子本身,經過測試確定可以監聽到應用本身被卸載的動作,但是在handleLog()方法中我能只能做些省時的操作,擼主測試可以發出短信,但是無法完成http的發送!例子本身是通過不斷的讀日志來監聽應用本身是否被卸載,因而是非常好電和性能的
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
相關經驗
相關資訊
相關文檔
目錄