Модераторы: javastic
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> The method getWindow() is undefined for the type 
:(
    Опции темы
wichujanin
Дата 2.4.2014, 23:05 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 8
Регистрация: 2.4.2014

Репутация: нет
Всего: нет



Хочу внутри сервиса выполнять свою функцию через определенный период.

Взял исходник из примера сервиса, дописал свою функцию, нажал Ctrl + Shift + O:
Код

package org.divenvrsk.examples.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class RepeatingAlarmService extends BroadcastReceiver {

    public void PrtSc()
    {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) 
        {
            File sdCard = Environment.getExternalStorageDirectory();
            File directory = new File(sdCard.getAbsolutePath() + "/ScreenShots");
            directory.mkdirs();
            int i = 0;
            String filename;
            File yourFile;
            do {
                i++;
                filename = "screenshot" + i + ".jpg";
                yourFile = new File(directory, filename);
            } while (yourFile.exists());
            Bitmap bitmap;
//Ошибка тут:                                !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            View view = getWindow().getDecorView().findViewById(android.R.id.content).getRootView();
            view.setDrawingCacheEnabled(true);
            bitmap = Bitmap.createBitmap(view.getDrawingCache());
            view.setDrawingCacheEnabled(false); 
            OutputStream fileOut = null;
            try {
                fileOut = new FileOutputStream(yourFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOut);
                fileOut.flush();
                fileOut.close();
            } 
            catch (FileNotFoundException e){
                e.printStackTrace();
            }        
            catch (IOException e){
                e.printStackTrace();
            }    
        }        
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
     PrtSc();
        Toast.makeText(context, "It's Service Time!", Toast.LENGTH_LONG).show();
        Log.v(this.getClass().getName(), "Timed alarm onReceive() started at time: " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
    }
}

Код

package org.divenvrsk.examples.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class OnBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent serviceLauncher = new Intent(context, ServiceExample.class);
            context.startService(serviceLauncher);
            Log.v(this.getClass().getName(), "Service loaded while device boot.");
        }
    }
}



Код

package org.divenvrsk.examples.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ServiceActivity extends Activity implements View.OnClickListener {

    Button buttonStart, buttonStop;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);

        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonStart:
                Log.v(this.getClass().getName(), "onClick: Starting service.");
                startService(new Intent(this, ServiceExample.class));
                break;
            case R.id.buttonStop:
                Log.v(this.getClass().getName(), "onClick: Stopping service.");
                stopService(new Intent(this, ServiceExample.class));
                break;
        }
    }
}



Код

package org.divenvrsk.examples.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

public class ServiceExample extends Service {

    public static final int INTERVAL = 10000; // 10 sec
    public static final int FIRST_RUN = 5000; // 5 seconds
    int REQUEST_CODE = 11223344;

    AlarmManager alarmManager;

    @Override
    public void onCreate() {
        super.onCreate();

        startService();
        Log.v(this.getClass().getName(), "onCreate(..)");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.v(this.getClass().getName(), "onBind(..)");
        return null;
    }

    @Override
    public void onDestroy() {
        if (alarmManager != null) {
            Intent intent = new Intent(this, RepeatingAlarmService.class);
            alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0));
        }
        Toast.makeText(this, "Service Stopped!", Toast.LENGTH_LONG).show();
        Log.v(this.getClass().getName(), "Service onDestroy(). Stop AlarmManager at " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
    }

    private void startService() {

        Intent intent = new Intent(this, RepeatingAlarmService.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + FIRST_RUN,
                INTERVAL,
                pendingIntent);

        Toast.makeText(this, "Service Started.", Toast.LENGTH_LONG).show();
        Log.v(this.getClass().getName(), "AlarmManger started at " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
    }
}


Где:
View view = getWindow().getDecorView().findViewById(android.R.id.content).getRootView(); 
getWindow подчеркивается красным, ошибка: The method getWindow() is undefined for the type RepeatingAlarmService
Как испарвить?

PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Android | Следующая тема »


 




[ Время генерации скрипта: 0.0603 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.